How to merge two json string in Python?

后端 未结 6 2090
醉酒成梦
醉酒成梦 2020-12-08 10:20

I recently started working with Python and I am trying to concatenate one of my JSON String with existing JSON String. I am also working with Zookeeper so I get the existing

6条回答
  •  佛祖请我去吃肉
    2020-12-08 10:59

    Merging json objects is fairly straight forward but has a few edge cases when dealing with key collisions. The biggest issues have to do with one object having a value of a simple type and the other having a complex type (Array or Object). You have to decide how you want to implement that. Our choice when we implemented this for json passed to chef-solo was to merge Objects and use the first source Object's value in all other cases.

    This was our solution:

    from collections import Mapping
    import json
    
    
    original = json.loads(jsonStringA)
    addition = json.loads(jsonStringB)
    
    for key, value in addition.iteritems():
        if key in original:
            original_value = original[key]
            if isinstance(value, Mapping) and isinstance(original_value, Mapping):
                merge_dicts(original_value, value)
            elif not (isinstance(value, Mapping) or 
                      isinstance(original_value, Mapping)):
                original[key] = value
            else:
                raise ValueError('Attempting to merge {} with value {}'.format(
                    key, original_value))
        else:
            original[key] = value
    

    You could add another case after the first case to check for lists if you want to merge those as well, or for specific cases when special keys are encountered.

提交回复
热议问题