问题:如何将字典转储到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树形图。

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:

{      
    "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.


回答 0

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

这是一种更简单的方法。

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

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

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.

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


回答 1

结合@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/

Combine the answer of @mgilson and @gnibbler, I found what I need was this:


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()

It this way, I got a pretty-print json file. The tricks print >> f, j is found from here: http://www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/


回答 2

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

当然,不可能完全保留顺序…但这只是字典的性质…

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

Of course, it’s unlikely that the order will be exactly preserved … But that’s just the nature of dictionaries …


回答 3

这应该给你一个开始

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

This should give you a start

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

回答 4

具有漂亮的打印格式:

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)

with pretty-print format:

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)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。