gpt4 book ai didi

python - Python 中联合多个嵌套 JSON

转载 作者:行者123 更新时间:2023-11-30 23:32:56 26 4
gpt4 key购买 nike

我有多个包含需要合并的关系数据的json文件,每个文件都有一个带有commonkey的记录,它是所有文件中的公共(public)键,在下面的示例中a0,a1是公共(public)键。该值是一个嵌套的如下所示的 Key1、key2 等多个键的字典,我需要合并多个 json 文件并获取如 dboutput.json 中所示的输出,其中文件名充当合并操作中的索引。这样的问题是related question它合并丢失的信息,但在我的情况下,我不希望任何替换现有键或跳过更新的更新,如果击中现有键,则会创建另一个由文件名索引的嵌套字典,如下所示:

示例:

文件 db1.json:

"a0": {        "commonkey": [            "a1",             "parentkeyvalue1"        ],         "key1": "kvalue1",         "key2": "kvalue2"        "keyp": "kvalue2abc"    }, "a1": { ...}

File db2.json:

"a0": {        "commonkey": [            "a1",             "parentkeyvalue1"        ],         "key1": "kvalue1xyz",         "key2": "kvalue2",        "key3": "kvalue2"    }, "a1": { ...}

Desired Output

File dboutput.json

"a0": {        "commonkey": [            "a1",             "parentkeyvalue1"        ],         "key1": {"db1":"kvalue1","db2":"kvalue1xyz"} ,        "key2": {"db1":"kvalue2","db2":"kvalue2"} ,        "key3": {"db2":"kvalue2"}        "keyp": {"db1":"kvalue2abc"}    }, "a1": { ...}

So how to do such lossless merges? Note "key2": {"db1":"kvalue2","db2":"kvalue2"} even if the key\value pairs are same they need to be stored separately. In effect the output is a union of all input files and has all entries from all other files.

Also

"commonkey": [
"a1",
"parentkeyvalue1"
],

所有文件都相同,因此无需重复

最佳答案

我终于成功了:

class NestedDict(collections.OrderedDict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value

def mergejsons(jsns):
##use auto vification Nested Dict
op=nesteddict.NestedDict()
for j in jsns:
jdata=json.load(open(j))
jname=j.split('.')[0][-2:]
for commnkey,val in jdata.items():
for k,v in val.items():
if k!='commonkey':
op[commnkey][k][jname]=v
if op[commnkey].has_key('commonkey'):
continue
else:
op[commnkey][k][jname]=v

关于python - Python 中联合多个嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19135805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com