Python - 组合 n 个不同的 json files/dictionaries(n 可能不同)

Python - Combining n different json files/dictionaries (n could vary)

我尝试用问题中的关键字搜索这个特定问题,但找不到好的解决方案。

假设我有一个 JSON 文件的列表(假设顶层总是字典):

"../data/Flickr_EXIF_0.json",
"../data/Flickr_EXIF_150.json",
"../data/Flickr_EXIF_300.json",
"../data/Flickr_EXIF_450.json",

问题是 combine/merge 将所有 json 个文件合并为一个文件。

这样做当然很简单,因为我们知道要合并多少 JSON 个文件,

with open("../data/Flickr_EXIF_0.json", "r") as jFl:
    obj1 = json.load(jFl)

with open("../data/Flickr_EXIF_150.json", "r") as jFl:
    obj2 = json.load(jFl) 

with open("../data/Flickr_EXIF_300.json", "r") as jFl:
    obj3 = json.load(jFl) 

with open("../data/Flickr_EXIF_450.json", "r") as jFl:
    obj4 = json.load(jFl) 

d = {**obj1, **obj2, **obj3, **obj4}

但是 你怎么说写一个可以组合未知数量的 JSONs 的函数。我正在寻找一个 pythonic 解决方案。

这是我的部分解决方案,它会引发错误:

def appendJSON(*inpFl):
    flObjs = []
    for fl in inpFl:
        with open(fl, "r") as jFl:
            flObjs.append(json.load(jFl))

    # something smart here! 
    itemsList = [list(objs.items()) for objs in flObjs]

    return dict(itemsList)

错误:

ValueError Traceback (most recent call last) in () 20 "../data/Flickr_EXIF_1350.json", 21 "../data/Flickr_EXIF_1500.json", ---> 22 "../data/Flickr_EXIF_1650.json")

in appendJSON(*inpFl) 7 itemsList = [objs.items() for objs in flObjs] 8 ----> 9 return dict(itemsList) 10 11 objs = appendJSON("../data/Flickr_EXIF_0.json",

ValueError: dictionary update sequence element #0 has length 150; 2 is required

itemsList 的示例调试值:

[[('5822864395',
   {'date': '2010-06-10 14:48:25',
    'height': 2592,
    'lat': 0.0,
    'long': 0.0,
    'orientation': 0,
    'width': 2818}),
   ('1458886548',
   {'date': '2007-09-22 02:59:20',
    'height': 768,
    'lat': 39.145372,
    'long': -84.508981,
    'orientation': 0,
    'width': 1024})]]

备用解决方案,

def appendJSON(*inpFl):
    flObjs = []
    for fl in inpFl:
        with open(fl, "r") as jFl:
            flObjs.append(json.load(jFl))

    for i in range(1,len(flObjs)):
        flObjs[0].update(flObjs[i])

    return flObjs[0]

我会先做一个通用的解决方案,然后如果 JSON 文件的顶层类型都相同(即所有 object/dict 或所有 array/list).

如果加载后混合了顶级类型(dict、list、value),则无论如何都无法组合它们。如果每个加载的数据都是字典或每个加载的都是列表,则只能将它们组合起来。如果您有一个组合,或者如果您在顶层有一个或多个值,则不能组合。

一般方法是创建一个空列表,.append()json.load() 加载的数据,同时跟踪 having、dict、list 或值:

def combine(json_file_names):
    combined = []
    have_dict = False
    have_list = False
    for file_name in json_file_names:
        data = json.load(file_name)
        combined.append(data)
        if isinstance(data, dict):
            have_dict = True
        elif isinstance(data, list):
            have_list = True
        else:
            have_list = have_dict = True

    # if have_list and have_dict have the same value, either there is nothing 
    # loaded or it's a mixed bag. In both cases you can't do anything
    if have_list == have_dict:  
        return combined
    if have_list:
        tmp = []
        for elem in combined:
            tmp.extend(elem)
    else:  # have_dict
        tmp = {}
        for elem in combined:
            tmp.update(elem)
    return tmp

请注意,在组合所有顶级字典时,您会覆盖以前加载的数据中的键值对。

由于json很容易转换为Python字典,你需要做的就是将所有json文件读入字典,合并所有字典,转换为json 并将其保存到文件中。