Search code examples
pythonpython-3.xconfigurationyamlpyyaml

Reading nested JSON dynamically


I am currently trying out something which I am unsure if it is possible.

I am trying to map API values from a JSON string (which has nested values) to a database field but I wish for it to be dynamic.

In the YAML example below, the key would be the database field name and the database field value would be where to obtain the information from the JSON string ("-" delimited for nested values). I am able to read the YAML config but what I don't understand is how to translate it to python code. If it were to be dynamic I have no idea how many [] I would have to put.

YAML: (PYYAML package)

employer: "properties-employer_name"
...
employee_name: "employee"

Python Code: (Python 3.8)

json_data = { properties: {employer_name: "XYZ"}, employee: "Sam" }

employer = json_data["properties"]["employer_name"]  # How Do I add [] based on how nested the value is dynamically?
employee = json_data["employee"]

Many thanks!


Solution

  • You could try something like this:

    def get_value(data, keys):
       # Go over each key and adjust data value to current level
       for key in keys:
         data = data[key]
       return data # Once last key is reached return value
    

    You would get your keys by splitting on '-' if that is how you have it in your yaml so in my example I just saved the value to a string and did it this way:

    employer = "properties-employer_name"
    keys = employer.split('-') # Gives us ['properties', 'employer_name']
    

    Now we can call our get_value function defined above:

    get_value(json_data, keys)
    

    Which returns 'XYZ'