辞書をJSONファイルにダンプするにはどうすればいいですか? 質問する

辞書をJSONファイルにダンプするにはどうすればいいですか? 質問する

次のような辞書があります:

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

以下に示すように、辞書を JSON ファイルにダンプする方法がわかりません。

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

これを Python で実行する方法はありますか?

ツリーマップを生成したいと考えていると推測できますd3

ベストアンサー1

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

これはもっと簡単な方法です。

コードの 2 行目では、ファイルresult.jsonが作成され、変数として開かれますfp

3 行目には、辞書が!sampleに書き込まれます。result.json

おすすめ記事