0

I am trying to update a dynamic json key value. But i am not able to the recursive function done. My JSON structure is

x = {
  "payload": {
    "name": "kabilan",
    "address": {
      "country": "value_to_change"
    }
  }
}

In the above json, path to "value_to_change" is ['payload']['address']['country'] which i store it as "payload.address.country" in db.

This nested json structure is dynamically created but i also know the key path. Please find the code that i have written to change it

y = "payload.address.country"
y1 = y.split('.')
for item in y1:
  if item == y1[-1]:
    x[item] = "india"
  else:
    x = x[item]
print(x)

This code returns

"country":"india"

. But i want the output as

{
  "payload": {
    "name": "kabilan",
    "address": {
      "country": "india"
    }
  }
}

I think i am missing recursive function here. But i am getting confused in it. Kindly help me to solve this. Thanks in advance

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Possible duplicate: [Checking a nested dictionary using a dot notation string ā€œa.b.c.d.eā€, automatically create missing levels](https://stackoverflow.com/questions/12414821/checking-a-nested-dictionary-using-a-dot-notation-string-a-b-c-d-e-automatica) – Anoop R Desai Sep 14 '19 at 10:44
  • 1
    Possible duplicate of [Checking a nested dictionary using a dot notation string "a.b.c.d.e", automatically create missing levels](https://stackoverflow.com/questions/12414821/checking-a-nested-dictionary-using-a-dot-notation-string-a-b-c-d-e-automatica) – Anoop R Desai Sep 14 '19 at 10:46

2 Answers2

3

Choose variable names that are more representative of what they represent. By the way, x is a dictionary, not a JSON, which would be a string representation of a data structure.

x = {
  "payload": {
    "name": "kabilan",
    "address": {
      "country": "value_to_change"
    }
  }
}

key_path = "payload.address.country"
d = x
keys = key_path.split('.')
last_key = keys.pop()
for key in keys:
    d = d[key]
d[last_key] = "india"
print(x)

Prints:

{'payload': {'name': 'kabilan', 'address': {'country': 'india'}}}
Booboo
  • 38,656
  • 3
  • 37
  • 60
1

Simply write a function:

def update_x_from_y(x, y):
    y = y.split('.')
    n = len(y)

    for idx, item in enumerate(y):
        if idx == n - 1:
            x[item] = "india"
        else:
            x = x[item]

x = {
    "payload": {
        "name": "kabilan",
        "address": {
            "country": "value_to_change"
        }
    }
}
y = "payload.address.country"

update_x_from_y(x, y)

print(x)
Dipen Dadhaniya
  • 4,550
  • 2
  • 16
  • 24