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

ar8*_*809 2 python comparison json file

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

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

这些都是 JSON 文件

file1

[
 {
    "name": "John Wood",
    "age": 35,
    "country": "USA"
 },
 {
    "name": "Mark Smith",
    "age": 30,
    "country": "USA"
 }
]
Run Code Online (Sandbox Code Playgroud)

file2

[
 {
    "name": "John Wood",
    "age": 35,
    "country": "USA"
 },
 {
    "name": "Mark Smith",
    "age": 30,
    "country": "USA"
 },
 {
    "name": "Oscar Bernard",
    "age": 25,
    "country": "Australia"
 }
]
Run Code Online (Sandbox Code Playgroud)

代码

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")
Run Code Online (Sandbox Code Playgroud)

我不习惯使用 JSON 进行编程或比较两个不同的文件。我希望帮助返回差异,并将丢失的对象复制并粘贴到 file1 中。我这里显示的是 file1 中的每个对象是否等于 file2 中的每个对象。因此,返回“等于”和“不等于”输出。

输出:

Equal
Not Equal
Not Equal
Not Equal
Equal
Not Equal
Run Code Online (Sandbox Code Playgroud)

我想返回如果 file1 不等于 file2 以及缺少哪个对象(“名称”)。之后,我希望能够使用 open("file2.json", "w") 将丢失的对象添加/复制到 file2 中。

小智 5

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}")
Run Code Online (Sandbox Code Playgroud)