0

I want to read a JSON value using a dynamic key using Python. For example, I have a JSON in the following format

{
  "Personal": {
    "Address": {
      "City": "Newyork",
      "Country": "USA"
    }
  },
  "number": 123,
  "object": {
    "a": "b",
    "c": "d",
    "e": "f"
  }
}

If I enter a string as "Personal.Address.City", I need to get city value using Python.

1
  • what specific problem are you facing? spliting the keys? parsing the json? accessing an element in a json object using a key? using a loop? Commented Dec 9, 2019 at 5:31

1 Answer 1

4

It seems like you have to split the key and look up level-by-level manually. I give two implementations below:

data = {
  "Personal": {
    "Address": {
      "City": "Newyork",
      "Country": "USA"
    }
  },
  "number": 123,
  "object": {
    "a": "b",
    "c": "d",
    "e": "f"
  }
}

key = 'Personal.Address.City'

def lookup_dot_separated_key(data, key):
    value = data
    for k in key.split('.'):
        value = value[k]
    return value

print(lookup_dot_separated_key(data, key))

def lookup_key_list(data, keys):
    if keys:
        return lookup_key_list(data[keys[0]], keys[1:])
    else:
        return data

print(lookup_key_list(data, key.split('.')))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.