简体   繁体   English

Python JSON Object Z9516DFB15F51C7EE19A4D46B8C0DBE1

[英]Python JSON Object append

I have loaded two json files in Python3.8, and I need to merge the two based on a condition.我在Python3.8中加载了两个json文件,需要根据一个条件合并这两个文件。

Obj1 = [{'account': '223', 'colr': '#555555', 'hash': True},
        {'account': '134', 'colr': '#666666', 'hash': True},
        {'account': '252', 'colr': '#777777', 'hash': True}]

Obj2 = [{'sn': 38796, 'code': 'df', 'id': 199, 'desc': 'jex - #777777- gg2349.252'},
        {'sn': 21949, 'code': 'se', 'id': 193, 'desc': 'jex - #555555 - gf23569'},
        {'sn': 21340, 'code': 'se', 'id': 3, 'desc': 'jex - #666666 - gf635387'}]

# What I am trying to get

Obj3 = [{'sn': 38796, 'code': 'df', 'id': 199, 'desc': 'jex - #777777- gg2349.252', 'account': '252', 'colr': '#777777', 'hash': True},
        {'sn': 21949, 'code': 'se', 'id': 193, 'desc': 'jex - #555555 - gf23569', 'account': '223', 'colr': '#555555', 'hash': True},
        {'sn': 21340, 'code': 'se', 'id': 3, 'desc': 'jex - #666666 - gf635387', 'account': '134', 'colr': '#666666', 'hash': True}]

I have tried from what I can gather everything on SO from append, extend etc but I fall short on the condition.我已经尝试从 append、扩展等中收集 SO 上的所有内容,但我在这个条件下达不到要求。

I need to be able to append elements in Obj1 to Obj2 at their correct place based on a condition that if the colr of Obj1 is mentioned in desc of Obj2 it should append that whole element from Obj1 into the correlated element of Obj2 .我需要能够将Obj1Obj2中的 append 元素放在正确的位置, Obj1 colr desc中提到了 Obj1 的Obj2 ,那么它应该 append 整个元素从Obj1Obj2的相关元素。 Or create a new Obj3 that I can print these updated values from.或者创建一个新的Obj3 ,我可以从中打印这些更新的值。

What I have tried and looked at thus far Append JSON Object , Append json objects to nested list , Appending json object to existing json object and a few others that also didn't help. What I have tried and looked at thus far Append JSON Object , Append json objects to nested list , Appending json object to existing json object and a few others that also didn't help.

Hope this makes sense and thank you希望这是有道理的,谢谢

Something simple like this would work.像这样简单的东西会起作用。

for i in range(len(Obj1)):
    for j in range(len(Obj2)):
        if Obj1[i]['colr'] in Obj2[j]['desc']:
            Obj1[i].update(Obj2[j])

print(Obj1)

One approach is to first create a dictionary mapping each color to the JSON element.一种方法是首先创建一个字典,将每种颜色映射到 JSON 元素。 You can do this as你可以这样做

colr2elem = {elem['colr']: elem for elem in json_obj1}

Then you can see which color to append applying a Regular Expression to the description and update json_obj2 dictionary (merge dictionaries).然后您可以看到 append 的颜色,将正则表达式应用于描述并更新json_obj2字典(合并字典)。

import re

for elem2 in json_obj2:
    elem1 = colr2elem.get(re.search('#\d+', elem2['desc']).group(0))
    elem2.update(elem1 if elem1 is not None else {})
Obj1 = [{'account': '223', 'colr': '#555555', 'hash': True},
                 {'account': '134', 'colr': '#666666', 'hash': True},
                 {'account': '252', 'colr': '#777777', 'hash': True}]

Obj2 = [{'sn': 38796, 'code': 'df', 'id': 199, 'desc': 'jex - #777777- gg2349.252'},
             {'sn': 21949, 'code': 'se', 'id': 193, 'desc': 'jex - #555555 - gf23569'},
             {'sn': 21340, 'code': 'se', 'id': 3, 'desc': 'jex - #666666 - gf635387'}]

Obj3 = []
for i in  Obj1:
    for j in Obj2:
        if i["colr"]==j["desc"][6:13] :
            a = {**j,**i}
            Obj3.append(a)
print(Obj3)

You can use element1['colr'] in element2['desc'] to check if elements from the first and second arrays match.您可以使用element1['colr'] in element2['desc']检查第一个和第二个 arrays 中的元素是否匹配。 Now, you can iterate over the second array and for each of its elements find the corresponding element from the first array by checking this condition:现在,您可以遍历第二个数组,并通过检查以下条件为它的每个元素从第一个数组中找到相应的元素:

json_obj3 = []
for element2 in json_obj2:
    for element1 in json_obj1:
        if element1['colr'] in element2['desc']:
            element3 = dict(**element1, **element2)
            json_obj3.append(element3)
            break  # stop inner for loop, because matched element is found

BTW, this can be written as single expression using nested list comprehension :顺便说一句,这可以使用嵌套列表理解写成单个表达式:

json_obj3 = [
    dict(**element1, **element2)
    for element1 in json_obj1
    for element2 in json_obj2
    if element1['colr'] in element2['desc']
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM