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

时间:2021-06-14 18:51:04

标签: python json file comparison

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

我希望能够从 file2 返回丢失的对象并将其写入 file1。

这些都是 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 进行编程或比较两个不同的文件。 我想帮助退回差异,基本上是复制和粘贴 将丢失的对象放入 file1。我在这里的内容显示了文件 1 中的每个对象 等于或不等于file2。因此,返回“相等”和“不相等”输出。

输出:

Equal
Not Equal
Not Equal
Not Equal
Equal
Not Equal

如果文件 1 不等于文件 2 和哪个对象(“名称”),我想返回 是缺失的那个。之后,我希望能够使用 open("file2.json", "w") 将该丢失的对象添加/复制到 file2 中。

2 个答案:

答案 0 :(得分:1)

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}")

答案 1 :(得分:1)

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}")