나는 변수 'data'에 저장된 JSON 데이터를 가지고 있다.
매번 서버에서 데이터를 가져올 필요가 없도록 테스트하기 위해 텍스트 파일에 쓰고 싶습니다.
현재 다음과 같이 시도하고 있습니다.
obj = open('data.txt', 'wb')
obj.write(data)
obj.close
그리고 다음 오류를 수신합니다.
"TypeError: dict가 아닌 문자열 또는 버퍼여야 합니다."
이걸 어떻게 고치죠?
실제 JSON 부분을 잊어버렸습니다. 즉, 'data'는 사전이며 아직 JSON 인코딩이 되지 않았습니다. 이렇게을(를) 작성하면 호환성이 극대화됩니다(Python 2 및 3).
import json
with open('data.json', 'w') as f:
json.dump(data, f)
최신 시스템(예: Python 3 및 UTF-8 지원)에서 더 나은 파일을 작성할 수 있습니다.
import json
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
Python 2에 대해 허용된 응답의 ascii-encoded가 아닌 utf8-encoded 파일을 가져오려면 다음을 사용합니다.
import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
f.write(json.dumps(data, ensure_ascii=False))
이 코드는 파이썬 3에서 더 단순하다.
import json
with open('data.txt', 'w') as f:
json.dump(data, f, ensure_ascii=False)
윈도에서는 open(오픈)이라는 open(개방)의 주장이 여전히 필요하다.
데이터의 인코딩된 복사본을 메모리에 저장하지 않고('dumps'의 결과) Python 2와 3 모두에서 테스트 링으로 utf8-encoded를 출력하려면 다음을 사용합니다.
import json, codecs
with open('data.txt', 'wb') as f:
json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)
'codecs.getwriter' 호출은 Python 3에서는 중복되지만 Python 2에서는 필수입니다
가독성 및 크기:
'ensure_ascii=Facebook'을 사용하면 가독성이 향상되고 크기가 작아집니다.
>>> json.dumps({'price': '€10'})
'{"price": "\\u20ac10"}'
>>> json.dumps({'price': '€10'}, ensure_ascii=False)
'{"price": "€10"}'
>>> len(json.dumps({'абвгд': 1}))
37
>>> len(json.dumps({'абвгд': 1}, ensure_ascii=False).encode('utf8'))
17
플래그 'sort=4, sort_keys=를 추가하여 가독성을 더욱 향상시킵니다."dump" 또는 "dump"의 인수에 대해 True (dinos66에서 제안한 바와 같이). 이렇게 하면 파일 크기가 약간 더 큰 json 파일에서 잘 들여쓰기된 정렬된 구조를 얻을 수 있습니다.
나는 앞서 말한 답변으로 약간 수정해서 대답할 것이고, 그것은 인간의 눈이 더 잘 읽을 수 있는 예쁜 JSON 파일을 쓰는 것이다. 이렇게 하려면 'sort_keys'를 'true'로, 'indent'를 공백 4자로 건네주면 된다. 또한 JSON 파일에 ASCII 코드가 기록되지 않도록 주의하십시오.
with open('data.txt', 'w') as outfile:
json.dump(jsonData, outfile, sort_keys = True, indent = 4,
ensure_ascii = False)
# -*- coding: utf-8 -*-
import json
# Make it work for Python 2+3 and with Unicode
import io
try:
to_unicode = unicode
except NameError:
to_unicode = str
# Define data
data = {'a list': [1, 42, 3.141, 1337, 'help', u'€'],
'a string': 'bla',
'another dict': {'foo': 'bar',
'key': 'value',
'the answer': 42}}
# Write JSON file
with io.open('data.json', 'w', encoding='utf8') as outfile:
str_ = json.dumps(data,
indent=4, sort_keys=True,
separators=(',', ': '), ensure_ascii=False)
outfile.write(to_unicode(str_))
# Read JSON file
with open('data.json') as data_file:
data_loaded = json.load(data_file)
print(data == data_loaded)
['제슨스트럼프'] 의 설명은 매개변수입니다 (https://docs.python.org/2/library/json.html # 기본 사용법):
Have a look at my 유틸리티 패키지 ['mpu'] (https://github.com/MartinThoma/mpu) 를 슈퍼 간단하고 기억하기 쉬운 1:
import mpu.io
data = mpu.io.read('example.json')
mpu.io.write('example.json', data)
{
"a list":[
1,
42,
3.141,
1337,
"help",
"€"
],
"a string":"bla",
"another dict":{
"foo":"bar",
"key":"value",
"the answer":42
}
}
'.j슨'
응용 프로그램의 다음 중요할 수 있습니다.
참고: [비교 데이터를 직렬화하지 형식식] (https://en.wikipedia.org/wiki/Comparison_of_data_serialization_formats)
구성 파일을 만들 수 있는 방법을 찾고 있는 경우에 대비해 것이 내 짧은 기사를 읽을 수 있는 것이 좋습니다 [구성 파일을 파이썬] (https://martin-thoma.com/configuration-files-in-python/)
그리스, 또는 기타 " exotic" 덤프합니다 너희가운데 오른길로 위한 노력을 하고 있다. 하지만 나 역시 같은 언어를 문제가 (unicode 오류뿐만) 와 같은 다른 어떤 이상한 문자를 평화를 상징하는 (\u262E) 또는 종종 포맷 등의 데이터를 json 으로 v2.03-00 Twitter& # 39 에 이 솔루션을 다음과 같을 수 있습니다 () 는 분명히 sort_keys 임의선택):
import codecs, json
with codecs.open('data.json', 'w', 'utf8') as f:
f.write(json.dumps(data, sort_keys = True, ensure_ascii=False))
예를 들어, 다음과 같은 백업하도록 phihag& # 39 의 대답: 이 코드는 파이썬 2 '에서 그의 답변은 제외하고는 브레이크를 TypeError: 유니코드 문자를 ascii 가 아닌 '아닌', 'str 경우 데이터를 포함하고 있어야 합니다. (파이썬 2.7.6, 데비안):
import json
data = {u'\u0430\u0431\u0432\u0433\u0434': 1} #{u'абвгд': 1}
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)
그러나 파이썬 3 이 제대로 작동합니다.
이전의 모든 대답이 슬라이드에서는 수정하십시오 매우 간단한 예:
#! /usr/bin/env python
import json
def write_json():
# create a dictionary
student_data = {"students":[]}
#create a list
data_holder = student_data["students"]
# just a counter
counter = 0
#loop through if you have multiple items..
while counter < 3:
data_holder.append({'id':counter})
data_holder.append({'room':counter})
counter += 1
#write the file
file_path='/tmp/student_data.json'
with open(file_path, 'w') as outfile:
print("writing file to: ",file_path)
# HERE IS WHERE THE MAGIC HAPPENS
json.dump(student_data, outfile)
outfile.close()
print("done")
write_json()
이 수락됨 오토메이티드 정상입니다. 하지만, 제가 json 으로 실행했음 " serializable" 아닙니다. 사용하는 오류.
내가 어떻게 이 here& # 39 의 고정 함께 '오픈 (# 39, & # 39 w& file-name.json" ";;;)' 를 출력:
"'우스푸스트라이트 (str (응답)"'
그런 것은 아니지만 좋은 수리입니다 json 으로 만든 파일을 갖지 않고 다만 큰따옴표 찾고 있다면 매우 빠르고 더러운.
Json 데이터를 다음과 같이 쓸 수 있는 파일
hist1 = [{'val_loss': [0.5139984398465246],
'val_acc': [0.8002029867684085],
'loss': [0.593220705309384],
'acc': [0.7687131817929321]},
{'val_loss': [0.46456472964199463],
'val_acc': [0.8173602046780344],
'loss': [0.4932038113037539],
'acc': [0.8063946213802453]}]
쓸 파일:
with open('text1.json', 'w') as f:
json.dump(hist1, f)