Python转储dict到json文件

hol*_*lys 184 python json dictionary

我有这样的字典:

sample = {'ObjectInterpolator': 1629,  'PointInterpolator': 1675, 'RectangleInterpolator': 2042}
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何将dict转储到json文件中,如下所示:

{      
    "name": "interpolator",
    "children": [
      {"name": "ObjectInterpolator", "size": 1629},
      {"name": "PointInterpolator", "size": 1675},
      {"name": "RectangleInterpolator", "size": 2042}
     ]
}
Run Code Online (Sandbox Code Playgroud)

有没有pythonic方式来做到这一点?

您可能猜到我想生成一个d3树形图.

moo*_*obi 329

import json
with open('result.json', 'w') as fp:
    json.dump(sample, fp)
Run Code Online (Sandbox Code Playgroud)

这是一种更简单的方法.

在第二行代码中,文件result.json被创建并作为变量打开fp.

在第三行,你的dict sample被写入result.json!

  • 提示:如果您不想写入文件,只看输出,请尝试将其重定向到`stdout:json.dump('SomeText',sys.stdout)` (4认同)
  • 这里要记住的好事是,除非您使用`OrderedDict`(python >2.7),否则不能保证以任何特定方式对键进行排序 (3认同)
  • @Dan-ish 你试过 json.dump(sample, fp, sort_keys=False ) 吗?假设我明白你的意思。 (2认同)
  • @Vijay,该函数称为“dump”(而不是“dumps”)。 (2认同)

hol*_*lys 35

结合@mgilson和@gnibbler的答案,我发现我需要的是这个:


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, j可以从这里找到:http: //www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/

  • Python 3.6中的'print(j,file = f)`(而不是`print >> f,j`) (13认同)
  • `print(j, file=f)` 对我不起作用,我也不需要做 J 部分。`d = {'a':1, 'b':2} print(d, file=open('sample.json', 'wt'))` 有效。 (3认同)

als*_*052 23

还想添加这个(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)
Run Code Online (Sandbox Code Playgroud)

更新(11-04-2021):所以我添加这个例子的原因是因为有时你可以使用该print()函数写入文件,这也展示了如何使用缩进(未缩进的东西是邪恶的!!)。然而,我最近开始学习线程,我的一些研究表明该print()语句并不总是线程安全的。因此,如果您需要线程,您可能需要小心这一点。


mgi*_*son 21

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

当然,订单不太可能完全保留......但这只是字典的本质......

  • 如果需要排序顺序,则json_string = json.dumps(d ,, sort_keys = True). (5认同)

Joh*_*ooy 12

这应该给你一个开始

>>> 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
    }
]
Run Code Online (Sandbox Code Playgroud)


jmh*_*let 9

使用漂亮的打印格式:

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)
Run Code Online (Sandbox Code Playgroud)

  • 您也可以将所有这些参数提供给“dump(sample, file, ...)”。不需要写入字符串的额外步骤。`dump` 内部以块的形式写入。这可能比首先编译一个(可能很大)字符串更有效。 (4认同)

dav*_*nte 6

如果您正在使用Path

Path('result.json').write_text(json.dumps(sample, indent=4) + '\n')
Run Code Online (Sandbox Code Playgroud)