【问题标题】:How to dump a dict to a JSON file?如何将字典转储到 JSON 文件?
【发布时间】:2013-06-07 06:54:54
【问题描述】:

我有一个这样的字典:

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

我不知道如何将 dict 转储到 JSON 文件,如下所示:

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

有没有pythonic方法可以做到这一点?

你可能猜到我想生成一个d3 树形图。

【问题讨论】:

  • 您能接受其中一个答案吗?

标签: python json dictionary


【解决方案1】:

这应该给你一个开始

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

【讨论】:

    【解决方案2】:
    d = {"name":"interpolator",
         "children":[{'name':key,"size":value} for key,value in sample.items()]}
    json_string = json.dumps(d)
    

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

    【讨论】:

    • json_string = json.dumps(d, , sort_keys=True) 如果需要排序顺序。
    【解决方案3】:

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

    【讨论】:

    • print(j, file=f) 在 Python 3.6 中(而不是 print >> f, j
    • print(j, file=f) 对我不起作用,我也不需要做 J 部分。 d = {'a':1, 'b':2} print(d, file=open('sample.json', 'wt')) 工作。
    • 您也可以使用indent创建格式化转储:json.dump(content, file, indent=4)
    【解决方案4】:
    import json
    with open('result.json', 'w') as fp:
        json.dump(sample, fp)
    

    这是一种更简单的方法。

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

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

    【讨论】:

    • @Danish 不知道。除非关于您的问题已经存在关于 SO 的问题,否则您应该创建一个新问题来描述您的问题。 (顺便说一句,我只是这些帖子的编辑)
    • 提示:如果您不想写入文件,并且只看到输出,请尝试将其重定向到stdout: json.dump('SomeText', sys.stdout)
    • @Dan-ish 你试过 json.dump(sample, fp, sort_keys=False ) 吗?假设我明白你的意思。
    • 这里要记住的一点是,除非您使用 OrderedDict (python >2.7),否则无法保证键以任何特定方式排序
    • @Vijay,这个函数叫做dump(不是dumps)。
    【解决方案5】:

    具有漂亮的打印格式:

    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)
    

    【讨论】:

    • 您也可以将所有这些参数提供给dump(sample, file, ...)。不需要写入字符串的额外步骤。 dump 内部以块的形式写入。这可能比先编译一个(可能很大的)字符串更有效。
    【解决方案6】:

    也想添加这个(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)
    

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

    【讨论】:

      【解决方案7】:

      如果您使用的是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')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-16
        • 2014-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多