programing

딕트를 JSON 파일에 덤프하는 방법

bestcode 2022. 11. 27. 11:33
반응형

딕트를 JSON 파일에 덤프하는 방법

나는 다음과 같은 구술이 있다.

sample = {'ObjectInterpolator': 1629,  'PointInterpolator': 1675, 'RectangleInterpolator': 2042}

아래와 같이 dict를 JSON 파일로 덤프하는 방법을 알 수 없습니다.

{      
    "name": "interpolator",
    "children": [
      {"name": "ObjectInterpolator", "size": 1629},
      {"name": "PointInterpolator", "size": 1675},
      {"name": "RectangleInterpolator", "size": 2042}
     ]
}

이것을 할 수 있는 비토닉적인 방법이 있나요?

이 경우, I가 RPG를 생성하기를 원할 것으로 생각됩니다.d3트리맵

import json
with open('result.json', 'w') as fp:
    json.dump(sample, fp)

이게 더 쉬운 방법이에요.

코드의 두 번째 줄에서 파일은result.json변수로 생성 및 열립니다.fp.

세 번째 줄에서 받아쓰기sample에 기입되다result.json!

@mgilson과 @gnibler의 답변을 종합하면, 필요한 것은 다음과 같습니다.


d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
j = json.dumps(d, indent=4)
f = open('sample.json', 'w')
print >> f, j
f.close()

이렇게 하면 예쁜 프린트의 json 파일을 얻을 수 있어요.요령print >> f, jhttp://www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/ 에서 입수할 수 있습니다.

d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)

python 3.7 이므로 dits 의 순서는 https://docs.python.org/3.8/library/stdtypes.html#mapping-types-dict 에서 유지됩니다.

사전은 삽입 순서를 유지합니다.키를 갱신해도 주문에는 영향을 주지 않습니다.삭제 후 추가된 키가 마지막에 삽입됩니다.

이것으로 깜짝 놀라실 겁니다.

>>> import json
>>> print json.dumps([{'name': k, 'size': v} for k,v in sample.items()], indent=4)
[
    {
        "name": "PointInterpolator",
        "size": 1675
    },
    {
        "name": "ObjectInterpolator",
        "size": 1629
    },
    {
        "name": "RectangleInterpolator",
        "size": 2042
    }
]

예쁜 인쇄 형식:

import json

with open(path_to_file, 'w') as file:
    json_string = json.dumps(sample, default=lambda o: o.__dict__, sort_keys=True, indent=2)
    file.write(json_string)

이것도 추가하고 싶었다(Python 3.7)

import json

with open("dict_to_json_textfile.txt", 'w') as fout:
    json_dumps_str = json.dumps(a_dictionary, indent=4)
    print(json_dumps_str, file=fout)

업데이트(11-04-2021) :그래서 제가 이 예를 추가한 이유는 가끔 이 예시를 사용할 수 있기 때문입니다.print()파일에 쓰는 기능과 들여쓰기 사용법도 보여줍니다(의도하지 않은 것은 사악합니다!!).그러나 나는 최근에 스레드에 대해 배우기 시작했고 내 연구의 일부에 의하면print()스테이트먼트가 항상 스레드 세이프인 것은 아닙니다.따라서 스레드가 필요한 경우 이 제품을 사용하는 데 주의를 기울일 수 있습니다.

사용하는 경우:

example_path = Path('/tmp/test.json')
example_dict = {'x': 24, 'y': 25}
json_str = json.dumps(example_dict, indent=4) + '\n'
example_path.write_text(json_str, encoding='utf-8')

언급URL : https://stackoverflow.com/questions/17043860/how-to-dump-a-dict-to-a-json-file

반응형