【发布时间】:2021-03-15 15:31:50
【问题描述】:
我有两个 json 数据,其中 json_main 和 json1 如下所示。我想检查 json1,如果 json_main 数据中有任何可用的详细信息,那么应该删除确切的详细信息和预期的结果,我看起来像下面显示的“结果 Result_json”。
例如:在json1数据""fields"中:{ "完整地址": "data2", “赫兹”:“文本2”, "ot": "doc2"" 在 json_main 数据中可用。所以我想从 json1 数据中删除它。
我尝试了python代码,但我不知道如何与json_main数据进行比较并删除json1数据。
json_main
[
{
"fields": {
"Full Address": "data1",
"hz": "text1",
"ot": "doc1"
}
},
{
"fields": {
"Full Address": "data2",
"hz": "text2",
"ot": "doc2"
}
}
]
json1
[
{
"fields": {
"Full Address": "data2",
"hz": "text2",
"ot": "doc2"
}
},
{
"fields": {
"Full Address": "data3",
"hz": "text3",
"ot": "doc3"
}
}
]
结果Result_json
[
{
"fields": {
"Full Address": "data3",
"hz": "text3",
"ot": "doc3"
}
}
]
Python
with open('writing_file.json', 'w') as w:
with open('reading_file.json', 'r') as r:
for line in r:
element = json.loads(line.strip())
if 'data2' in element:
del element['data2']
w.write(json.dumps(element))
【问题讨论】:
-
如果只有一个字段相同怎么办?你为什么要明确检查
'data2'? -
然后结果在 json 正文中没有给出任何内容。
标签: python json delete-operator