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

2

2 Answers 2

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'}}}
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.