以下是4个JSON文件:
-
3个JSON文件有3个关键字段:name、rating和year
-
1 JSON只有两个关键字段:名称、评级(无年份)
[
{
"name": "Apple",
"year": "2014",
"rating": "21"
},
{
"name": "Pear",
"year": "2003",
"rating": ""
},
{
"name": "Pineapple",
"year": "1967",
"rating": "60"
},
]
[
{
"name": "Pineapple",
"year": "1967",
"rating": "5.7"
},
{
"name": "Apple",
"year": "1915",
"rating": "2.3"
},
{
"name": "Apple",
"year": "2014",
"rating": "3.7"
}
]
[
{
"name": "Apple",
"year": "2014",
"rating": "2.55"
}
]
[
{
"name": "APPLE",
"rating": "+4"
},
{
"name": "LEMON",
"rating": "+3"
}
]
在所有4个文件中搜索“Apple”时,您希望返回1个名称、1年和4个评级:
name: Apple (closest match to search term across all 4 files)
year: 2014 (the MOST COMMON year for Apple across first 3 JSONs)
rating: 21 (from JSON1)
3.7 (from JSON2)
2.55 (from JSON3)
+4 (from JSON4)
现在假设JSON3(或任何JSON)已经
不匹配
相反
返回以下内容。假设在至少一个文件中至少有一个匹配项。
name: Apple (closest match to search term across all 4 files)
year: 2014 (the MOST COMMON year for Apple across first 3 JSONs)
rating: 21 (from JSON1)
3.7 (from JSON2)
Not Found (from JSON3)
+4 (from JSON4)
如何在Python中获得这个输出?
此问题类似于中的示例代码
Python - Getting the intersection of two Json-Files
,除了有4个文件外,还有1个文件缺少
评级
到目前为止,我只得到了上面两组JSON:
import json
with open('1.json', 'r') as f:
json1 = json.load(f)
with open('2.json', 'r') as f:
json2 = json.load(f)
json2[0]['name'] = list(set(json2[0]['name']) - set(json1[0]['name']))
print(json.dumps(json2, indent=2))
我从中得到了输出,但它与我想要达到的目标不匹配。例如,这是输出的一部分:
{
"name": [
"a",
"n",
"i",
"P"
],
"year": "1967",
"rating": "5.7"
},