使用Python写入JSON文件

5

我需要在Python中编写一个JSON文件,但是我已经看到的所有内容(如json.dump)都不能满足我的要求...

我有一个结构,我只想在其中添加一些内容。 比如,我想加入一个输入服务:

{
"Serial_011": "011",
"Servers_011":
    [
        {
            "hostname": "srv-a.11",
            "ipv4_address": "0.0.0.0",
            "services":
                [
                    {
                        "uri": "http://www.google.fr/1",
                        "expected_code": 200
                    },
                    {
                        "uri": "http://www.google.fr/2",
                        "expected_code": 200
                    }
                ]
        },
        {
            "hostname": "nsc-srv-b.11",
            "ipv4_address": "0.0.0.0",
            "services":
                [
                    {
                        "uri": "http://www.google.fr/3",
                        "expected_code": 200
                    },
                    {
                        "uri": "http://www.google.fr/4",
                        "expected_code": 200
                    }
                ]
        }
    ]
}

提前致谢


3
将JSON读取为对象,向该对象添加您的信息并再次序列化(如果需要,则使用prettyprinting)。 - MKesper
3
https://www.google.com - RAVI
1
如果您没有特殊的文件格式,那么添加一些非结尾部分的通常方法是加载它、修改它,然后将整个东西写回。 (在大型文件上,您可以尝试使用流式处理方法) - janbrohl
我已经使用'with open...'打开了JSON文件,但问题是写入。 - msommer
@M_S,我已经为这个问题发布了一个答案。你可以尝试一下吗?你肯定可以使用我的答案中的with子句。谢谢。 - Sreejith Menon
显示剩余2条评论
1个回答

2

在我使用Python处理JSON对象时,我会牢记以下4种方法:

  • json.dumps(<a Python字典对象>) - 将Python字典对象转换成JSON格式的字符串
  • json.dump(<a Python字典对象>, <文件对象>) - 将JSON格式的数据写入文件对象中
  • json.loads(<一个字符串>) - 从字符串中读取JSON对象
  • json.load(<一个JSON文件>) - 从文件中读取JSON对象

另外需要注意的一点是,在Python中,jsondict是等价的。

假设文件内容存储在文件addThis.json中,而你已经有一个现有的JSON对象,它存储在文件existing.json中。下面的代码应该能完成这项任务。

import json

existing = json.load(open("/tmp/existing.json","r"))
addThis = json.load(open("/tmp/addThis.json","r"))

for key in addThis.keys():
     existing[key] = addThis[key]

json.dump(exist,open("/tmp/combined.json","w"),indent=4)

编辑: 假设addThis的内容不是在文件中,而是要从控制台读取。

import json

existing = json.load(open("/tmp/existing.json","r"))

addThis = input()
# paste your json here.
# addThis is now simply a string of the json content of what you to add

addThis = json.loads(addThis) #converting a string to a json object.
# keep in mind we are using loads and not load

for key in addThis.keys():
     existing[key] = addThis[key]

json.dump(exist,open("/tmp/combined.json","w"),indent=4)

那么在existing.json中我将放置当前的json,在addThis.json中,我编写我想要添加的内容,使用input(),并且结果将是conbined.json吗? - msommer
请澄清一下,要添加的内容是从input()中读取的吗? - Sreejith Menon
@M_S 我已经添加了从 input() 读取新 json 内容的代码。如果这个方法有效,请点赞并确认答案。谢谢。 - Sreejith Menon
它在循环中... json.dump 中存在什么? - msommer
你能再清楚一点吗? - Sreejith Menon
显示剩余2条评论

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