2017-08-31 1 views
1

私はJSONファイルの数があります一般的な共有メンバーに基づいて他のJSONファイルからJSONを生成するにはどうすればよいですか?

json_files = ['file1.json', 'file2.json', 'file3.json'] 

その内容:

Pythonの使用
# file1.json 
{ 
    "foo": ["bar", "baz"], 
    "hello": ["wonderful", "world"] 
} 

# file2.json 
{ 
    "foo": ["bar", "xxx", "baz"], 
    "hello": ["world"] 
} 

# file3.json 
{ 
    "foo": ["bar", "boo"], 
    "hello": ["cruel", "world"] 
} 

を、私はこれらのファイルと出力のみ一般を含む新しい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') 

答えて

1

はフラットな構造(なし任意のネスト)を仮定すると、辞書のキー交差点を見つけ、その後、各共通鍵のアイテム交差点を見つけ、それを反復。

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 
関連する問題