如何将字典转储到JSON文件?

449

我有一个类似这样的字典:

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

我无法弄清如何将字典转储到JSON文件中,如下所示:

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

有没有一种Pythonic的方法来做到这一点?

你可能猜到我想生成一个 d3 treemap。


1
你能接受其中一个答案吗? - Robson
7个回答

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

这是一个更简单的方法。

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

在第三行中,你的字典sample被写入到result.json中!


1
@Danish 不知道。除非在SO上已经有关于你的问题的问题,否则你应该创建一个新的问题来描述你的问题。(顺便说一句,我只是这些帖子的编辑者) - user
17
提示:如果您不想将其写入文件,只想查看输出,请尝试将其重定向到stdout: json.dump('SomeText', sys.stdout) - Arindam Roychowdhury
2
@Dan-ish,你尝试过使用json.dump(sample, fp, sort_keys=False)吗?假设我理解你的意思。 - Chris Larson
3
这里需要记住的一件好事是,除非您使用 OrderedDict(Python >2.7),否则不能保证键以任何特定方式排序。 - ford prefect
2
@Vijay,这个函数叫做dump(不是dumps)。 - moobi
显示剩余8条评论

57

结合@mgilson和@gnibbler的回答,我找到了我需要的内容:

d = {
    "name": "interpolator",
    "children": [{
        'name': key,
        "size": value
        } for key, value in sample.items()]
    }
j = json.dumps(d, indent=4)
with open('sample.json', 'w') as f:
    print >> f, j
以这种方式,我得到了一个漂亮的JSON文件。 技巧print >> f, j是从这里找到的: http://www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/

31
Python 3.6 中使用 print(j, file=f) 来输出到文件(代替 Python 2 中的 print >> f, j)。 - mjkrause
3
"print(j, file=f)" 对我没用,我也不需要做J部分。 "d = {'a':1, 'b':2} print(d, file=open('sample.json', 'wt'))" 可以使用。 - H S Rathore
1
您还可以使用 indent 创建格式化的转储:json.dump(content, file, indent=4) - deshu
1
indent=4,这就是我在寻找的东西! - user3503711

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

自Python 3.7版本起,字典(dict)的顺序被保留。https://docs.python.org/3.8/library/stdtypes.html#mapping-types-dict

字典(Dictionaries)保留插入顺序。请注意,更新键不会影响顺序。删除后添加的键将被插入到末尾。


7
如果想要按排序后的顺序,可以使用json.dumps(d, sort_keys=True)来将d转换成json字符串。 - Chris Larson

21

还想补充一点(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)

更新(2021年11月4日): 我添加此示例的原因是因为有时您可以使用 print() 函数写入文件,并且这还显示了如何使用缩进(未缩进的内容是“邪恶的”!)。然而,我最近开始学习线程编程,我的一些研究表明 print() 语句并不总是线程安全的。因此,如果您需要线程编程,您可能需要小心使用它。


17

这应该可以给你一个起点

>>> 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
    }
]

17

采用漂亮打印格式:

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)

6
你也可以将所有这些参数提供给dump(sample, file, ...)。不必要额外地写入字符串。dump内部会逐块写入,这可能比先编译(可能很大)的字符串更有效率。 - Adrian W

5
如果您正在使用 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')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接