Here’s a method to extract the first and last items from nested JSON using Python logic and methods. This was a question in an HCL interview.

python parse nested json
Photo by cottonbro studio on Pexels.com

Table of contents

  1. Nested JSON
  2. Python Logic to extract data from JSON
  3. Conclusion

Nested JSON

JSON data is similar to dictionary data. Better check whether the items’ data is in the dictionary format or not.

data= {"isbn": "123-456-222", 
 "author":
{
"lastname": "Doe",
"firstname": "Jane"
},
"editor":
{
"lastname": "Smith",
"firstname": "Jane"
},
"title": "The Ultimate Database Study Guide",
"category": ["Non-Fiction", "Technology"]
}

Python Logic to extract data from JSON

Python Logic to get the last name and first name of the editor. The first code block explains how to extract the last name and the second code block explains how to extract the first name. The isinstance() method checks if the ‘v’ is in dictionary format before it proceeds further.

# THIS PROGRAM EXTRCATS EDITOR FIRST NAME AND LAST NAME FROM THE NESTED JSON

# CODE TO GET EDITOR FIRST NAME
for k, v in data.items():
if k == "editor" and isinstance(v, dict):
editor_firstname=v["firstname"]
print("Editor Firstname: ", editor_firstname)

# CODE TO GET EDITOR LAST NAME
if k == "editor" and isinstance(v, dict):
editor_lastname=v["lastname"]
print("Editor Lastname: ", editor_lastname)

Output

Editor Firstname:  Jane
Editor Lastname: Smith

Conclusion

By utilizing Python logic to parse the nested JSON data, we successfully extracted the first name and last name of the editor. With the provided code, we were able to obtain the following information:

  • Editor Firstname: Jane
  • Editor Lastname: Smith

This demonstrates the effective use of Python methods and logic to extract specific data from nested JSON structures.