티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to dump a dict to a JSON file?

JSON 파일에 딕셔너리를 덤프하는 방법은 무엇인가요?

 문제 내용 

I have a dict like this:

이렇게 딕셔너리가 있습니다:
sample = {'ObjectInterpolator': 1629,  'PointInterpolator': 1675, 'RectangleInterpolator': 2042}

 

I can't figure out how to dump the dict to a JSON file as showed below:

저는 아래와 같이 JSON 파일에 딕셔너리를 덤프하는 방법을 알 수 없습니다:
{      
    "name": "interpolator",
    "children": [
      {"name": "ObjectInterpolator", "size": 1629},
      {"name": "PointInterpolator", "size": 1675},
      {"name": "RectangleInterpolator", "size": 2042}
     ]
}

 

Is there a pythonic way to do this?

이것을 파이썬스럽게 할 수 있는 방법이 있을까요?

 

You may guess that I want to generate a d3 treemap.

d3 트리맵을 생성하려고 한다고 추측할 수 있습니다.

 

 

 

 높은 점수를 받은 Solution 

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

This is an easier way to do it.

이것은 더 쉬운 방법입니다.

 

In the second line of code the file result.json gets created and opened as the variable fp.

코드의 두 번째 줄에서는 파일 result.json이 만들어지고 변수 fp로 열립니다.

 

In the third line your dict sample gets written into the result.json!

세 번째 줄에서는 샘플 딕셔너리가 result.json에 작성됩니다!

 

 

 

 가장 최근 달린 Solution 

If you're using Path:

Path를 사용하는 경우:
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')

 

 

출처 : https://stackoverflow.com/questions/17043860/how-to-dump-a-dict-to-a-json-file

반응형
댓글
공지사항
최근에 올라온 글