json转储到文件

时间:2014-01-08 13:00:35

标签: python json

你有一个json文件如下 -

{
    "Account": {
        "name": "demo_account_1",
        "Containers": [
            {
                "name": "abcd",
                "created_at": "1189090948.18945",
            },
            {
                "name": "pqrs",
                "created_at": "1234558.18945",
            }
        ]
    }

现在我想在此python脚本中填充此文件,以便我可以向Account或Containers添加更多条目。即插入容器后文件看起来像 -

{
    "Account": {
        "name": "demo_account_1",
        "Containers": [
            {
                "name": "abcd",
                "created_at": "1189090948.18945",
            },
            {
                "name": "pqrs",
                "created_at": "1234558.18945",
            },
            {
                "name": "mnop",
                "created_at": "100000.12345",
            }
        ]
    }

1 个答案:

答案 0 :(得分:4)

你拥有的文件无效JSON(缺少一个右大括号,而且有一些逗号太多。

但是如果你有一个像

这样的有效文件
{
    "Account": {
        "name": "demo_account_1",
        "Containers": [
            {
                "name": "abcd",
                "created_at": "1189090948.18945"
            },
            {
                "name": "pqrs",
                "created_at": "1234558.18945"
            }
        ]
    }
}

然后这个代码片段会做你想要的:

import json
with open("test.json") as infile:
    j = json.load(infile)

j["Account"]["Containers"].append({"name": "mnop", "created_at": "100000.12345"})

with open("test.json", "w") as outfile:
    json.dump(j, outfile, indent=4)