Places is a list and not a dictionary. This line below should therefore not work:

print(data['places']['latitude'])

You need to select one of the items in places and then you can list the place's properties. So to get the first post code you'd do:

print(data['places'][0]['post code'])
Answer from agrinh on Stack Overflow
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-access-nested-keys-in-a-python-json-object-395034
How to access nested keys in a Python JSON object | LabEx
The get() method approach is generally preferred for its readability and conciseness when dealing with nested JSON structures. It allows you to provide default values at each level of nesting.
๐ŸŒ
Hackers and Slackers
hackersandslackers.com โ€บ extract-data-from-complex-json-python
Extract Nested Data From Complex JSON
December 22, 2022 - Below we see how such a request would be made via Python's requests library. ... origins: Physical place (or places) representing where our trip begins. This value can be passed as a city name, address, or other formats; essentially what you'd expect from using the Google Maps app. destinations: Equivalent of the origins parameter for trip destination(s) ... """Fetch and extract JSON data from Google Maps.""" import requests from config import API_KEY def google_maps_distance(): """Fetch distance between two points.""" endpoint = "https://maps.googleapis.com/maps/api/distancematrix/json" params = { 'units': 'imperial', 'key': API_KEY, 'origins': 'New York City, NY', 'destinations': 'Philadelphia,PA', 'transit_mode': 'car' } resp = requests.get(endpoint, params=params) return resp.json()
๐ŸŒ
Like Geeks
likegeeks.com โ€บ home โ€บ python โ€บ how to get json value by key in python
How To Get JSON Value by Key in Python
Using the get() method to access values provides a safer alternative to direct key access. This method is useful in handling cases where a key might not exist in the JSON object, thus avoiding potential KeyError exceptions.
๐ŸŒ
Reddit
reddit.com โ€บ r/python โ€บ jsonparse library. extract from deeply nested json based on key's and key value
r/Python on Reddit: jsonparse library. Extract from deeply nested JSON based on key's and key value
July 8, 2022 -

Hello. I wrote a straightforward library to extract values from JSON data key:values once it is a python object (list or dict) via json.loads().

jsonparse github

I initially made this to practice dfs/bfs. I have since cleaned it up a bunch, documented it, created tests, etc. and I'm happy to show off.

Use-case: I use this to find values via key(s) or key:value pairs in deeply nested JSON data from API's.

Examples in the README.md

I'm happy for any feedback that you are willing to share!

๐ŸŒ
Quora
quora.com โ€บ How-do-I-extract-nested-JSON-data-in-python
How to extract nested JSON data in python - Quora
Answer (1 of 5): [code]for item in array_name: print item.get("arrayElementName").get("NestedarrayElementName") [/code]
๐ŸŒ
Claudia Kuenzler
claudiokuenzler.com โ€บ blog โ€บ 1395 โ€บ how-to-iterate-nested-json-dict-search-specific-value-print-key-python
How to iterate through a nested JSON, search for a specific value and print the key with Python
February 27, 2024 - After investing quite some time for a solution, I eventually came across an answer on StackOverflow, which offers a function doing a "deep iteration lookup" into nested dictionaries. After having adjusted the "parse_json_recursively" function to my needs, the function now looks like this: def parse_json_recursively(json_object, target_key, *parent_key): if type(json_object) is dict and json_object: for key in json_object: print("Key: {}, Parent Key: {}".format(key, parent_key)) if key == target_key: # Found Health key print("Health status of {} is {}".format(parent_key, json_object[key]['Health'])) print("---------------------------") else: # Continue iterating parse_json_recursively(json_object[key], target_key, key)
๐ŸŒ
Medium
ankushkunwar7777.medium.com โ€บ get-data-from-large-nested-json-file-cf1146aa8c9e
Working With Large Nested JSON Data | by Ankush kunwar | Medium
January 8, 2023 - To extract data from a nested JSON object using recursion, you can use a function that iterates through the object and extracts the desired values. Here is an example of how you might do this: def extract_values(obj, key): """Pull all values ...
Find elsewhere
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ latest โ€บ how to extract nested dictionary data in python?
How to extract Nested Dictionary Data in Python? | Towards Data Science
March 5, 2025 - Even the most skilled programmer can be brought to tears when working with a JSON object that consists of a mix of deeply nested data structures. The process of extracting the values can feel messy and disorganized at best. The more data there is, the bigger the mess. ... In this tutorial, Iโ€™ll walk you through a step-by-step method to extract the values you need from any JSON. A word of warning: this tutorial is not meant for newbies to JSON, lists or dictionaries. If youโ€™ve never heard of a list index or a dictionary key-value pair, I would suggest reviewing one of the many great tutorials available on the web or YouTube.
Top answer
1 of 3
19

It is a bit lenghty, but in that example above:

In [1]: import json

In [2]: s = """\
   ...: {
   ...:   "A": {
   ...:     "B": {
   ...:       "unknown": {
   ...:         "1": "F",
   ...:         "maindata": [
   ...:           {
   ...:             "Info": "TEXT"
   ...:           }
   ...:         ]
   ...:       }
   ...:     }
   ...:   }
   ...: }"""

In [3]: data = json.loads(s)

In [4]: data['A']['B']['unknown']['maindata'][0]['Info']
Out[4]: u'TEXT'

You basically treat it as a dictionary, passing the keys to get the values of each nested dictionary. The only different part is when you hit maindata, where the resulting value is a list. In order to handle that, we pull the first element [0] and then access the Info key to get the value TEXT.

In the case of unknown changing, you would replace it with a variable that represents the 'known' name it will take at that point in your code:

my_variable = 'some_name'
data['A']['B'][my_variable]['maindata'][0]['Info']

And if I would have actually read your question properly the first time, if you don't know what unknown is at any point, you can do something like this:

data['A']['B'].values()[0]['maindata'][0]['Info']

Where values() is a variable containing:

[{u'1': u'F', u'maindata': [{u'Info': u'TEXT'}]}]

A single-item list that can be accessed with [0] and then you can proceed as above. Note that this is dependent on there only being one item present in that dictionary - you would need to adjust a bit if there were more.

2 of 3
8

You can use a recursive function to dig through every layer and print its value with an indent

def recurse_keys(df, indent = '  '):
    ''' 
    import json, requests, pandas
    r = requests.post(...)  
    rj = r.json() # json decode results query
    j = json.dumps(rj, sort_keys=True,indent=2)            
    df1 = pandas.read_json(j)         
    '''
    for key in df.keys():
        print(indent+str(key))
        if isinstance(df[key], dict):
            recurse_keys(df[key], indent+'   ')
recurse_keys(df1)
๐ŸŒ
Pybites
pybit.es โ€บ articles โ€บ case-study-how-to-parse-nested-json
Case Study: How To Parse Nested JSON - Pybites
June 3, 2022 - A common strategy is to flatten the original JSON by doing something very similar like we did here: pull out all nested objects by concatenating all keys and keeping the final inner value.
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-what-are-best-practices-for-extracting-values-from-nested-python-json-objects-395100
What are best practices for extracting values from nested Python JSON objects | LabEx
Based on the techniques we've explored in this lab, here are the best practices for extracting values from nested JSON objects: Use the get() method instead of direct indexing to provide default values for missing keys.
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ latest โ€บ how to access nested data in python
How to access nested data in Python | Towards Data Science
January 20, 2025 - If you look in the picture of the data above, you can see that the first key is "ApartmentBuilding". By writing the name of the key in square brackets we get the corresponding value which is another dictionary.
๐ŸŒ
Bcmullins
bcmullins.github.io โ€บ parsing-json-python
Parsing Nested JSON Records in Python - Brett Mullins โ€“ Researcher - Data Scientist
For analyzing complex JSON data in Python, there arenโ€™t clear, general methods for extracting information (see here for a tutorial of working with JSON data in Python). This post provides a solution if one knows the path through the nested JSON to the desired information. ... { "employees": [ { "name": "Alice", "role": "dev", "nbr": 1 }, { "name": "Bob", "role": "dev", "nbr": 2 } ], "firm": { "name": "Charlie's Waffle Emporium", "location": "CA" } } This record has two keys at the top level: employees and firm. The value for the employees key is a list of two objects of the same schema; each object has the keys name, role, and nbr.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to check if nested json has key/value pair when when subcategory names are not consistent.
r/learnpython on Reddit: How to check if nested json has key/value pair when when subcategory names are not consistent.
October 2, 2021 -

I have the following json structure file:

parent1
-------subcat1
----------------subsubcat1
----------------....
----------------subsubcatN
-------....
-------subcatN

parent2
-------subcat1
----------------subsubcat1
----------------....
----------------subsubcatN
-------....
-------subcatN

and each subsubcat has list of dictionaries in which one key - value pair can be 'uid':'12563'.

I need to check if parent1, parent2 has this par, or none of them... problem i subcat and subsubcat keys are not consistent (they change depending on json file), deepness stays the same.

Basically i need smng like

if json['parent1][*][*][*]['uid']  == 12563

but it's not gonna work :)

๐ŸŒ
Stack Exchange
salesforce.stackexchange.com โ€บ questions โ€บ 391891 โ€บ how-can-i-parse-nested-json-and-form-a-final-map-with-all-the-key-and-values-fro
apex - how can i parse nested json and form a final map with all the key and values from the nested json with mulltiple arrays - Salesforce Stack Exchange
In the example above, the json_obj ... the JSON object as a Python dictionary. The for loop will iterate over the key-value pairs in the dictionary, allowing you to access each key and value. You can then do whatever you need to do with the key and value, such as print them or use them in some other way. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... 1 Custom controller, default object values, and validation. How can I get all three ...
๐ŸŒ
Tek-Tips
tek-tips.com โ€บ home โ€บ forums โ€บ software โ€บ programmers โ€บ languages โ€บ python
Extracting Values from a nested JSON | Tek-Tips
February 26, 2022 - [COLOR=#a020f0]import[/color] json DBG_INFO = [COLOR=#008b8b]False[/color] my_dictionary = { [COLOR=#ff00ff]"[/color][COLOR=#ff00ff]body[/color][COLOR=#ff00ff]"[/color]: [COLOR=#ff00ff]"[/color][COLOR=#ff00ff]{'Classes': [{'Name': 'Loans', 'Score': 0.7328000068664551}, {'Name': 'Mortgage', 'Score': 0.14270000159740448}, {'Name': 'Savings', 'Score': 0.0649000033736229}], 'ResponseMetadata': {'RequestId': 'eb8e3b9f-2116-4398-8af4-e15a7ae609fb', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'eb8e3b9f-2116-4398-8af4-e15a7ae609fb', 'content-type': 'application/x-amz-json-1.1', 'content
๐ŸŒ
GitHub
gist.github.com โ€บ douglasmiranda โ€บ 5127251
Find all occurences of a key in nested python dictionaries and lists - http://stackoverflow.com/questions/9807634/find-all-occurences-of-a-key-in-nested-python-dictionaries-and-lists ยท GitHub
So for the 'Item' included above, starting at "results": and nesting node to "transcription", the parsed values need to be: Sender Account Number, 1957-3549-2 (repeating items) 'for' Much thanks for any assistance!! ... Thanks for the help. Python3 users should replace dictionary.iteritems() with dictionary.items().
๐ŸŒ
Quora
quora.com โ€บ What-is-the-best-way-to-parse-a-nested-JSON-structure-using-Python
What is the best way to parse a nested JSON structure using Python? - Quora
ALGORITHM to Extract (key,val) pair in a nested JSON_OBJECT: ... I have attached link to the python script that extracts each key,value pair.
๐ŸŒ
Robotastemtraining
robotastemtraining.com โ€บ read โ€บ how-do-you-get-all-values-by-key-with-json-and-python
How Do You Get All Values by Key with JSON and Python?
Extracting all values associated with a specific key from a JSON object in Python is straightforward with the right approach. By defining a recursive function, you can traverse complex JSON structures and collect the desired values. This technique is especially useful when working with nested ...