对于一个项目,我需要用 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
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
提前致谢
当我在 python 中使用 JSON 对象时,我会记住 4 个方法。
json.dumps(<a python dict object>)- 给出由 python dict 对象形成的 json 的字符串表示形式json.dump( <a python dict object>,<file obj>)- 在文件对象中写入一个json文件json.loads(<a string>)- 从字符串中读取 json 对象json.load(<a json file>)- 从文件中读取 json 对象。下一个要记住的重要事情是jsons 和dict在 python 中是等效的。
因此,我们可以说,文件内容位于 file 内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)
Run Code Online (Sandbox Code Playgroud)
编辑:假设 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5354 次 |
| 最近记录: |