changing JSON value with other JSON in Python

Viewed 41

on a nested JSON object, I would like to modify values and adding a JSON Object. Assume a JSON Object like this:

{
    "key1": "value1",
    "key2": {
        "key2_1": "value2_2 ",
        "key2_2": {
            "key2_2_1 ": "value2_2_1"
        },
        "key2_3": "value2_3",
        "key2_4": {
            "key2_4_1": [{
                "key2_4_1_1a": "value2_4_1_1a",
                "key2_4_1_2a": "value2_4_1_2a"
            }, {
                "key2_4_1_1b": "value2_4_1_1b",
                "key2_4_1_2b": "value2_4_1_2b"
            }]
        }
    },
    "key3": {
        "key3_1": "value3_2 ",
        "key3_2": {
            "key3_2_1 ": "value3_2_1"
        },
        "key3_3": "value3_3",
        "key3_4": {
            "key3_4_1": {
                "key3_4_1_1": "value3_4_1_1"
            }
        }
    }

}

now the JSON will be recursive iterated to search for a specific value. The replacement value can be a string

repl = 'MyString'

a dict string

repl = '''{"MyKey": [{"MyKey1": "MyValye1"},{"MyKey2": "MyValye2"}]}'''

or a list

repl = '''[{"MyKey1": "MyValye1"},{"MyKey2": "MyValye2"}]'''

so after I found the key where the replacement to add, I would like to replace the existing value for the given key. eg for the string:

a[key] = repl

How I can do this for dict or list replacements?

The result could be depending on the replacement variable, the string eg in "key2_1", the dict in "key2_2_1" or the list in "key2_3". The keys where string,dict or list are inserted are examples.

{
    "key1": "value1",
    "key2": {
        "key2_1": "MyString",
        "key2_2": {
            "key2_2_1 ": {"MyKey": [{"MyKey1": "MyValye1"},{"MyKey2": "MyValye2"}]}
        },
        "key2_3": [{"MyKey1": "MyValye1"},{"MyKey2": "MyValye2"}],
        "key2_4": {
            "key2_4_1": [{
                "key2_4_1_1a": "value2_4_1_1a",
                "key2_4_1_2a": "value2_4_1_2a"
            }, {
                "key2_4_1_1b": "value2_4_1_1b",
                "key2_4_1_2b": "value2_4_1_2b"
            }]
        }
    }

}

i have a search function:

def searchNreplace(data, search_val, replace_val):
    if isinstance(data, list):
        return [searchNreplace(listd, search_val, replace_val) for listd in data]
    if isinstance(data, dict):
        return {dictkey: searchNreplace(dictvalue, search_val, replace_val) for dictkey, dictvalue in data.items()}
    return replace_val if data == search_val else data

print(searchNreplace(data, "key3", repl))
1 Answers

If you really don't struggle with finding a key, you can use json library to parse your string to object and just assign it as str.

import json

repl = """{"MyKey": [{"MyKey1": "MyValye1"},{"MyKey2": "MyValye2"}]}"""
a[key] = json.loads(repl)

After that you can dump content back to file

with open("my_file", "w+") as f:
    json.dump(a, f)
Related