简体   繁体   English

在python中合并Json对象?

[英]Merge Json Objects in python?

I have two json objects.我有两个 json 对象。 Both may have common keys, Some present only in first object, while some present only in second.两者可能有共同的键,有些只出现在第一个对象中,而有些只出现在第二个对象中。 When I come these two objects the structure of objects should not change.当我来到这两个对象时,对象的结构不应该改变。 Only a new level of keys will be added such as the specifying for which object that value belongs to.只会添加一个新级别的键,例如指定该值属于哪个对象。 Even the structure of json objects represent a hierarchy whose levels are not fixed.甚至 json 对象的结构也代表了一个层次不固定的层次结构。

a = {"parent1" : { "childa1" : { "grandchilda11" : { "data": values}, 
                                 "grandchilda12" :{"data" : values }
                                }
                               "data" : values 
                 }
                 { "childa2" : { "grandchilda21" : { "data": values}, 
                                 "grandchilda22" :{"data" : values }
                                }
                               "data" : values 
                 }                  
     }
b = { "parent1" : { "childa1" : { "grandchilda11" : { "data": values}, 
                             "grandchilda12" :{"data" : values }
                            }
                           "data" : values 
             }
             { "childa2" : { "grandchilda21" : { "data": values}, 
                             "grandchilda22" :{"data" : values }
                            }
                           "data" : values 
             },
     "parent2" : { "childb1" : { "grandchildb11" : { "data": values}, 
                             "grandchildb12" :{"data" : values }
                            }
                           "data" : values 
             }
             { "childb2" : { "grandchildb21" : { "data": values} 

                            }
                           "data" : values 
             }

 }

The resultant should combine this type of json string .结果应该结合这种类型的 json string 。 The data level here contains directly values while in the resultant it should be like which object it belongs acting as key and then values .这里的数据级别直接包含值,而在结果中它应该像它属于哪个对象作为键,然后是值。

 "data" : { "a" : values , "b":values}

I think this may be what you're looking for.我想这可能就是你要找的。

If you have data dictionaries a and b you can call the below function using merge(a, b) to merge the two like you've said.如果您有数据字典ab您可以使用merge(a, b)调用以下函数来merge(a, b)两者,就像您所说的那样。 It does rely on the assumption that both dictionaries have the same structure to them .它确实依赖于两个字典具有相同结构的假设

def merge(a, b):
    if type(a) is str:
        return { 'a': a, 'b': b }

    else:
        for key in a:
            a[key] = merge(a[key], b[key])

    return a

Try this:试试这个:

def merge(obj1, obj2):
for key in obj2:
    obj1[key] = obj2[key]
return obj1

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

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