比较两个JSON文件并返回差异



我发现了一些类似的问题。问题是,这些解决方案都不适合我,有些过于先进。我正在尝试读取这两个JSON文件,并返回它们之间的差异。

我希望能够从文件2中返回丢失的对象,并将其写入文件1。

这两个都是JSON文件

file1
[
{
"name": "John Wood",
"age": 35,
"country": "USA"
},
{
"name": "Mark Smith",
"age": 30,
"country": "USA"
}
]

file2
[
{
"name": "John Wood",
"age": 35,
"country": "USA"
},
{
"name": "Mark Smith",
"age": 30,
"country": "USA"
},
{
"name": "Oscar Bernard",
"age": 25,
"country": "Australia"
}
]

代码

with open("file1.json", "r") as f1:
file1 = f1.read()
item1 = json.loads(file1)
print(item1)
with open("file2.json", "r") as f2:
file2 = f2.read()
item2 = json.loads(file2)
print(item2)
# Returns if that index is the same
for v in range(len(item1)):
for m in range(len(item2)):
if item2[v]["name"] == item1[m]["name"]:
print("Equal")
else:
print("Not Equal")

我不习惯使用JSON编程或比较两个不同的文件。我想帮助返回差异,基本上是复制粘贴文件1中缺少的对象。这里显示的是文件1中的每个对象等于或不等于file2。因此;等于";以及";不相等";输出

输出:

Equal
Not Equal
Not Equal
Not Equal
Equal
Not Equal

如果file1不等于file2就是那个失踪的人。之后,我希望能够使用with open("file2.json","w"(将丢失的对象添加/复制到file2中。

with open("file1.json", "r") as f1:
file1 = json.loads(f1.read())
with open("file2.json", "r") as f2:
file2 = json.loads(f2.read())
for item in file2:
if item not in file1:
print(f"Found difference: {item}")
file1.append(item)
print(f"New file1: {file1}")
file1=[
{
"name": "John Wood",
"age": 35,
"country": "USA"
},
{
"name": "Mark Smith",
"age": 30,
"country": "USA"
}
]
file2=[
{
"name": "John Wood",
"age": 35,
"country": "USA"
},
{
"name": "Mark Smith",
"age": 30,
"country": "USA"
},
{
"name": "Oscar Bernard",
"age": 25,
"country": "Australia"
}
]
for item in file2:
if item['name'] not in [x['name'] for x in file1]:
print(f"Found difference: {item}")
file1.append(item)
print(f"New file1: {file1}")

相关内容

  • 没有找到相关文章

最新更新