Home >Backend Development >Python Tutorial >How do you extract nested values from a complex JSON structure?
Extracting Nested JSON Values
Problem:
When parsing JSON data, you may encounter complex and nested structures like this one:
<code class="json">{'name': 'ns1:timeSeriesResponseType', 'declaredType': 'org.cuahsi.waterml.TimeSeriesResponseType', 'scope': 'javax.xml.bind.JAXBElement$GlobalScope', 'value': {'queryInfo': {'creationTime': 1349724919000, 'queryURL': 'http://waterservices.usgs.gov/nwis/iv/', 'criteria': {'locationParam': '[ALL:103232434]', 'variableParam': '[00060, 00065]'}, 'note': [{'value': '[ALL:103232434]', 'title': 'filter:sites'}, {'value': '[mode=LATEST, modifiedSince=null]', 'title': 'filter:timeRange'}, {'value': 'sdas01', 'title': 'server'}]}}, 'nil': False, 'globalScope': True, 'typeSubstituted': False}</code>
You want to extract a specific value, such as the 'creationTime' field.
Solution:
1. Navigate the Data Structure:
To extract the 'creationTime' value, we need to navigate the nested structure using keys:
<code class="python">my_dict['key1']['key2']['key3']</code>
2. Example Code:
To obtain the 'creationTime' value, use the following code:
<code class="python">creation_time = my_dict['value']['queryInfo']['creationTime']</code>
3. Determining the Path to Data:
To determine the path to a specific data element, examine the structure of the JSON response:
4. More General Approach:
If you encounter an unknown nested JSON structure, you can use a recursive function to navigate and retrieve the desired value:
<code class="python">def get_nested_value(data, path): if isinstance(data, dict): if path[0] in data: return get_nested_value(data[path[0]], path[1:]) else: return None # Raise an error if the key doesn't exist elif isinstance(data, list): if len(path) == 0: return data else: return get_nested_value(data[path[0]], path[1:]) else: return data value = get_nested_value(my_dict, ['value', 'queryInfo', 'creationTime'])</code>
The above is the detailed content of How do you extract nested values from a complex JSON structure?. For more information, please follow other related articles on the PHP Chinese website!