如何从其他JSON文件生成基于共享成员的JSON?
问题描述:
我有一些JSON文件:如何从其他JSON文件生成基于共享成员的JSON?
json_files = ['file1.json', 'file2.json', 'file3.json']
它们的内容:
# file1.json
{
"foo": ["bar", "baz"],
"hello": ["wonderful", "world"]
}
# file2.json
{
"foo": ["bar", "xxx", "baz"],
"hello": ["world"]
}
# file3.json
{
"foo": ["bar", "boo"],
"hello": ["cruel", "world"]
}
使用Python,我想分析这些文件和输出一个新的JSON文件,该文件将只包含常用共享密钥/值:
# Generated JSON
{
"foo": ["bar"],
"hello": ["world"]
}
这怎么能实现?
这是我到目前为止有:
import json
def read_json(filename):
"""Read JSON, return dict"""
with open(filename, 'r') as data_file:
return json.load(data_file)
def write_json(dictionary, filename):
"""Write dictionary to JSON"""
with open(filename, 'w') as data_file:
json.dump(dictionary, data_file, indent=4)
def compare(dicts):
"""Generate JSON with commonly shared members"""
<LOOP HERE>
return common_members
if __name__ == '__main__':
f1 = read_json('file1.json')
f2 = read_json('file2.json')
f3 = read_json('file3.json')
dicts = [f1, f2, f3]
common_members = compare(dicts)
write_json(common_members, 'common_members.json')
答
假设一个平面结构(无任意嵌套),找到词典的关键路口,然后遍历它,找到每个公共密钥项目交集。
from functools import reduce
def compare(dicts):
common_members = {}
common_keys = reduce(lambda x, y: x & y, map(dict.keys, dicts))
for k in common_keys:
common_members[k] = list(reduce(lambda x, y: x & y, [set(d[k])
for d in dicts]))
return common_members