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
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-parse-nested-json-in-python
How to Parse Nested JSON in Python - GeeksforGeeks
July 23, 2025 - It builds a dictionary with the same nested structure, making it easier to access specific values later. In this example, the pd.json_normalize function from the Pandas library is utilized to flatten the nested JSON data into a Pandas DataFrame.
🌐
Reddit
reddit.com › r/learnpython › better way to parse insanely complex nested json data
r/learnpython on Reddit: Better way to parse insanely complex nested json data
August 19, 2024 -

Hi all,

Long time programmer here, but new to Python. This will be a long and, I think, complicated issue, so appreciate anyone who reads through it all and has any suggestions. I've looked up different ways to pull this data and don't seem to be making any progress. I'm sure there's a much better way.

I'm writing a program that will connect to our library to pull a list of everything we have checked out and I want to output a sorted list by due date and whether it has holds or not. I've got the code working to log in and pull a json data structure, but I cannot get it to export the data in the correct order. The json data is(to me) hideously complex with some data(due date) in one section and other data in another section. I'm able to pull the fields I want, but keeping them together is proving challenging.

For example, the title and subtitle are in the 'bibs/briefinfo' section with a key value of 'title' or 'subtitle'. Due Date is also in the 'checkouts' section with a key value of 'dueDate'. When I loop through them, though, the Titles are in one order, the due dates are in another order and the subtitles another.

I used BeautifulSoup because it's a webpage with json in it, so used BS to read the webpage.

I'm wanting to pull the following fields for each book so I can display the info for each book:

title, subtitle, contentType from briefinfo section

duedate from checkouts section

heldcopies and availablecopies from the availability section

Here's the pertinent section of my code:

soup = BeautifulSoup(index_page.text, 'html.parser')
            all_scripts = soup.find_all('script', {"type":"application/json"})

            for script in all_scripts:
                jsondata = json.loads(script.text)
                print(jsondata)
                
                output = []
                for i in item_generator(jsondata, "bibTitle"):
                    ans = {i}
                    print(i)
                    output.append(ans)

                for i in item_generator(jsondata, "dueDate"):
                    ans = {i}
                    output.append(ans)

                print("Subtitle----------------------")
                for i in item_generator(jsondata, "subtitle"):
                    ans = {i}
                    print(i)
                    output.append(ans)

print(output)

Here's the json output from my print statement so I can see what I'm working with. I tried to format it so it's easier to read. I removed a lot of other elements to keep the size down. Hopefully I didn't break any of the brackets.

{

'app':

{

'coreCssFingerprint': '123123123',

'coreAssets':

{

'cdnHost': 'https://xyz.com',

'cssPath': '/dynamic_stylesheet',

'defaultStylesheet': 'xyz.css'

},

},

'entities':

{

'listItems': {},

'cards': {},

'accounts':

{

'88888888':

  {
  'barcode': '999999999',
  'expiryDate': None, 
  'id': 88888888, 
  }

},

'shelves':

  {
  '88888888': 
  	{
  	'1111222222': 

{

'id': 1111222222,

'metadataId': 'S00A1122334',

'shelf': 'for_later',

'privateItem': True,

'dateAdded': '2023-12-30',

},

  	}
  }, 

'users':

  {
  '88888888': 
  	{ 
  	'accounts': \[88888888\], 
  	'status': 'A', 
  	'showGroupingDebug': False, 
  	'avatarUrl': '', 
  	'id': 88888888, 
  	}
  }, 
  'eventPrograms': {}, 
  'checkouts': 
  	{
  	'112233445566778899': 

{

'checkoutId': '112233445566778899',

'materialType': 'PHYSICAL',

'dueDate': '2024-08-26',

'metadataId': 'S99Z000000',

'bibTitle': "The Lord of the Rings"

},

  	'998877665544332211': 

{

'checkoutId': 998877665544332211',

'materialType': 'PHYSICAL',

'dueDate': '2024-08-26',

'metadataId': 'S88Y00000',

'bibTitle': 'The Lord of the Rings'

},

  	}, 
  'eventSeries': {}, 
  'catalogBibs': {},
  'bibs': 
  	{
  	'S88Y00000': 

{

'id': 'S88Y00000',

'briefInfo':

{

'superFormats': ['BOOKS', 'MODERN_FORMATS'],

'genreForm': [],

'callNumber': '123.456',

'authors': ['Tolkien, J.R.R.'],

'metadataId': 'S88Y00000',

'jacket':

{

'type': 'hardcover',

'local_url': None

},

'contentType': 'FICTION',

'format': 'BK',

'subtitle': 'The Two Towers',

'title': 'The Lord of the Rings',

'id': 'S88Y00000',

},

'availability':

{

'heldCopies': 0,

'singleBranch': False,

'metadataId': 'S88Y00000',

'statusType': 'AVAILABLE',

'totalCopies': 3,

'availableCopies': 2

}

},

'S77X12345':

{

'id': 'S77X12345',

'briefInfo':

{

'superFormats': ['BOOKS', 'MODERN_FORMATS'],

'genreForm': [],

'callNumber': '123.457',

'authors': ['Tolkien, J.R.R.'],

'metadataId': 'S77X12345',

'jacket':

{

'type': 'hardcover',

'local_url': None

},

'contentType': 'FICTION',

'format': 'BK',

'subtitle': 'The Fellowship of the Ring',

'title': 'The Lord of the Rings',

'id': 'S77X12345',

},

'availability':

{

'heldCopies': 0,

'singleBranch': False,

'metadataId': 'S77X12345',

'statusType': 'AVAILABLE',

'totalCopies': 2,

'availableCopies': 1

}

}

Anyone know of a better way to parse this data? Thanks!

Top answer
1 of 3
5
Two suggestions: First, when you want to print a json thing, you can do print(json.dumps(thing, indent=2)). This will apply indentation and newlines to make it clearer what the nested structure is. Second, the input data is what it is - but internal to your code you don't have to keep it that way. My suggestion would be to make a dataclass with the fields you care about, and write a classmethod for that that class to extract what you care about from the json. Then in your code, use instances of your class. I'm on my phone right now, but I'll edit with a small example of what I mean in a little bit. gross_nested_json = { 'books': [ { 'name': 'whatever', 'details1': { 'due_date': 'whenever', }, 'details2': { 'whatever_else': 'thing', } } ] } import dataclasses import typing as ty @dataclasses.dataclass class BookInfo: # If you're not familiar with these, google python dataclass, they're nice name: str due_date: str whatever: str @classmethod def from_gross_json(cls, gross_json: dict) -> ty.Self: return cls( name=gross_json['name'], due_date=gross_json['details1']['due_date'] whatever=gross_json['details2']['whatever_else'] ) books = [BookInfo.from_gross_json(gross_json) for gross_json in gross_nested_json['books'] You'll have to adjust for the pecularities of your particular input data, but if you make the data less gross for within your code consumption, it'll make the rest of your program nicer to write.
2 of 3
2
That's a rather awkward structure alright. Are the records to be linked by metadataId? [In]: for checkout in data['entities']['checkouts'].values(): print(checkout['bibTitle'], checkout['dueDate'], checkout['metadataId']) for bib in data['entities']['bibs'].values(): print(bib['briefInfo']['title'], bib['briefInfo']['subtitle'], bib['briefInfo']['metadataId']) print(bib['availability']['heldCopies'], bib['availability']['availableCopies']) [Out]: # The Lord of the Rings 2024-08-26 S99Z000000 # The Lord of the Rings 2024-08-26 S88Y00000 # The Lord of the Rings The Two Towers S88Y00000 # 0 2 # The Lord of the Rings The Fellowship of the Ring S77X12345 # 0 1
🌐
Medium
medium.com › @mayurkoshti12 › how-to-work-with-nested-json-data-in-python-bbf51f5231c7
How to Work with Nested JSON Data in Python | Medium
October 3, 2024 - Loading JSON: We start by loading the JSON response into a Python dictionary using json.loads(). Navigating the Structure: Using the get() method, we safely navigate through the nested structure to access the list of users.
🌐
Bcmullins
bcmullins.github.io › parsing-json-python
Parsing Nested JSON Records in Python - Brett Mullins
This is how both ‘Alice’ and ‘Bob’ are returned; since the value of employees is a list, the nesting is split on both of its elements and each of the values for name are appended to the output list. If obj is a single dictionary/JSON record, then this function returns a list containing the desired information, and if obj is a list of dictionaries/JSON records, then this function returns a list of lists containing the desired information.
🌐
Pybites
pybit.es › articles › case-study-how-to-parse-nested-json
Case study: How to parse nested JSON – Pybites
So the JSON response is structured in the following way: ... this root element has only two children, “author” and “entry”, from which I am only interested in “entry” · “entry” is a list of objects and each object has a set of properties like “author”, “link” and ,”im:rating” ... The most simple property is an object with just a “label” key and a value. More complex properties like “author” are again nested
🌐
DEV Community
dev.to › mandrewcito › nested-json-to-python-object--5ajp
Nested json to python object - DEV Community
January 29, 2019 - import json class AppConfiguration(object): def __init__(self, data=None): if data is None: with open("cfg.json") as fh: data = json.loads(fh.read()) else: data = dict(data) for key, val in data.items(): setattr(self, key, self.compute_attr_value(val)) def compute_attr_value(self, value): if type(value) is list: return [self.compute_attr_value(x) for x in value] elif type(value) is dict: return AppConfiguration(value) else: return value
🌐
GeeksforGeeks
geeksforgeeks.org › python › iterate-through-nested-json-object-using-python
Iterate Through Nested Json Object using Python - GeeksforGeeks
July 23, 2025 - In this example, the Python code defines a function, `iterate_nested_json_for_loop`, which uses a for loop to recursively iterate through a nested JSON object and print key-value pairs.
Find elsewhere
🌐
Medium
medium.com › @ferzia_firdousi › multi-level-nested-json-82d29dd9528
Deeply Nested JSON, json.normalize, pd.read_json | Medium
May 3, 2023 - We load it into JSON and introduce the .json_normalize() function for straightening the nested key-value pair.
🌐
Python.org
discuss.python.org › python help
processing nested json data - Python Help - Discussions on Python.org
July 13, 2025 - Hi, i need help to flatten the below json data by removing from “Answers” where “answer1” is null(‘’) : “body”: [ { “responseId”: 1, “answers”: [ { “answer1”: “”, “questionId”: “r67be312f34474793b802cdb35a719e5f” }, { “answer1”: { “id”: 1, “order”: 3, “displayText”: “Fair” }, "questionId": "r932bd3d18d4e4af2ba8174333c86a5dc" }, { "answer1": "7 to 9 years", "questionId": "r44d182a9e27d4b0c90286...
🌐
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 - Here is an example of how to parse a JSON string in Python: import json # Some JSON data json_data = '{"name": "John", "age": 30, "city": "New York"}' # Parse the JSON data data = json.loads(json_data) # Print the data print(data) This will parse the JSON data and store it in a dictionary. You can access the data in the dictionary like this: name = data['name'] age = data['age'] city = data['city'] 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.
🌐
Hackers and Slackers
hackersandslackers.com › extract-data-from-complex-json-python
Extract Nested Data From Complex JSON
December 22, 2022 - To use a better example, I recently used our json_extract() function to fetch lists of column names and their data types from a database schema. As separate lists, the data looked something like this: column_names = ['index', 'first_name', 'last_name', 'join_date'] column_datatypes = ['integer', 'string', 'string', 'date'] ... These two lists are directly related; the latter describes the former. How can this be useful? By using Python's zip method!
🌐
TecAdmin
tecadmin.net › using-nested-json-data-in-python
Working with Nested JSON Data in Python – TecAdmin
April 26, 2025 - A nested JSON object is a JSON object that contains other JSON objects or arrays as its values.
🌐
Esri Community
community.esri.com › t5 › python-questions › python-to-generate-dynamic-nested-json-string › td-p › 257817
Solved: Python to Generate Dynamic Nested JSON String - Esri Community
December 11, 2021 - Greetings, Using python and ArcPy search cursors, I've extracted list(s) of dictionaries containing normalized key value pairs originating from specific tables but residing in a denormalized database layer. In the same script, I am now creating a JSON string with an object containing field & value pair arrays [] that that are to contain the keys and values (key value pairs) I've already distilled into lists of dictionary structures.
🌐
Medium
medium.com › refined-and-refactored › api-requests-in-python-p3-working-with-nested-json-data-8c447763430c
API Requests in Python (P3): Working with nested JSON Data | by Alice Bui | Joon Solutions | Medium
November 6, 2024 - import pandas as pd import json def extract_values(obj, keys): """ Extracts values of multiple keys from a nested JSON structure. Args: obj: The nested JSON object. keys: A list of keys to extract.
🌐
Towards Data Science
towardsdatascience.com › home › latest › how to flatten deeply nested json objects in non-recursive elegant python
How to Flatten Deeply Nested JSON Objects in Non-Recursive Elegant Python | Towards Data Science
March 5, 2025 - The function "flatten_json_iterative_solution" solved the nested JSON problem with an iterative approach. The idea is that we scan each element in the JSON file and unpack just one level if the element is nested.
🌐
Codementor
codementor.io › community › working with json data in python
Working With JSON Data in Python | Codementor
May 5, 2020 - import json def checkList(ele, prefix): for i in range(len(ele)): if (isinstance(ele[i], list)): checkList(ele[i], prefix+"["+str(i)+"]") elif (isinstance(ele[i], str)): printField(ele[i], prefix+"["+str(i)+"]") else: checkDict(ele[i], prefix+"["+str(i)+"]") def checkDict(jsonObject, prefix): for ele in jsonObject: if (isinstance(jsonObject[ele], dict)): checkDict(jsonObject[ele], prefix+"."+ele) elif (isinstance(jsonObject[ele], list)): checkList(jsonObject[ele], prefix+"."+ele) elif (isinstance(jsonObject[ele], str)): printField(jsonObject[ele], prefix+"."+ele) def printField(ele, prefix): p
🌐
LabEx
labex.io › tutorials › python-how-to-efficiently-traverse-and-manipulate-nested-python-json-objects-395061
How to efficiently traverse and manipulate nested Python JSON objects | LabEx
Discover how to effectively navigate and manipulate complex nested JSON data structures in Python. Learn techniques to efficiently extract, update, and transform JSON objects for your Python applications.
🌐
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 - The technical documentation says a JSON object is built on two structures: a list of key-value pairs and an ordered list of values. In Python Programming, key-value pairs are dictionary objects and ordered list are list objects. In practice, the starting point for the extraction of nested data starts with either a dictionary or list data structure.
🌐
Quora
quora.com › How-do-I-extract-nested-JSON-data-in-python
How to extract nested JSON data in python - Quora
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.