首页 > 解决方案 > 比较 JSON 文件中的多个字典?

问题描述

现在我有一个如下所示的 JSON 文件:

"suggested":[{
    "city": "Berlin",
    "location": "Europe",
    "hotels": true,
    "restaurants": true,
    "rivers": false},
    {
        "city": "Andorra",
        "location": "Global",
        "hotels": false,
        "restaurants": true,
        "rivers": true
    }]

我想将分割在字典中的那个 JSON 文件与这个“参考”JSON 文件进行比较:

"master":[{
    "city": "",
    "location": "Europe",
    "hotels": true,
    "restaurants": false,
    "rivers": false
}]

我的目标是将 JSON 中键的值与 JSON 文件"master"中的内部字典的值进行比较"suggested",并返回它们有多少匹配项的打印。例如:

"Berlin" matches with "Master" in (3) fields.

现在我用一个简单的函数在 python 中打开了我的 JSON 文件:

def openJsonFile(file):
    with open (file) as json_data:
        workData = json.load(json_data)
        return(workData)

这个函数循环打开的文件:

def compareJsonFiles(suggested, master):
    matches = 0
    for key in suggested.keys():
        value = suggested[key]
        if key not in master:
            print ("{0} doesn't have value in {1}".format(key, master))
        else:
            if master[key] == value:
                print("for key %s values match" % key)
                matches + 1
    print(matches)

但是当我尝试通过字典时,我得到了这个错误:

AttributeError: 'list' object has no attribute 'keys'

更新: 我制作了这个函数,试图将 json 列表中的每个值作为单独的字典传递。

def jsonToDict(file):
for lsdt in file:
    newListDic = file[lsdt]
    for key in newListDic.keys():
        value = newListDic[key]
        print(value)

它可以给我一个听写。但它提示:

TypeError: list indices must be integers or slices, not dict

如何遍历 JSON 文件中的多个字典并将键值与另一个 JSON 文件进行比较?

PS:我已经搜索了将近两天没有成功,所以如果帖子发生的第一件事不是“标记为重复标志”,我会很高兴。

标签: pythonjson

解决方案


master的节点是列表,而不是字典。如果您确定 master 始终只保存一个条目,请通过

compareJsonFiles(suggested_data, master_data[0])

推荐阅读