Home > Backend Development > Python Tutorial > How do you extract nested values from a complex JSON structure?

How do you extract nested values from a complex JSON structure?

Linda Hamilton
Release: 2024-11-02 15:53:29
Original
723 people have browsed it

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>
Copy after login

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>
Copy after login

2. Example Code:

To obtain the 'creationTime' value, use the following code:

<code class="python">creation_time = my_dict['value']['queryInfo']['creationTime']</code>
Copy after login

3. Determining the Path to Data:

To determine the path to a specific data element, examine the structure of the JSON response:

  • Each key-value pair in the JSON structure represents a path segment.
  • To access a nested value, simply concatenate the path segments with '[]'.

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template