Convert JSON to Python Object (Non Nested, Nested & Multiple Object)
This article explains how to convert JSON data to Python native object for different cases.
Converting JSON data to native Python object is quite useful when you're dealing with data obtained from API or JSON data loaded from file.
To convert JSON data to Python object, there are different methods. In this article, we create simple class
to do it and use @staticmethod
decorator. This is the most effective way to do it. You can use @classmethod
as well with small modification.
Starting from non nested single object case, we cover non nested multiple object & nested multiple object to clear the concept.
Non-nested Simple Case
Suppose you have following JSON data in file named single_student.json
:
{ "student_id": "BCE001", "department": "Civil", "name": "Anisha Dahal", "email": "anisha@email.com" }
Python Source Code
import json
class Student:
def __init__(self,student_id, department, name, email):
self.student_id = student_id
self.department = department
self.name = name
self.email = email
@staticmethod
def create_from_json(data):
json_dictionary = json.loads(data)
return Student(**json_dictionary)
def __str__(self):
return "<Student {0}>".format(self.name)
with open("single_student.json","r") as json_data:
student_json = json_data.read()
print("Json object read from file:")
print("------------------------------")
print(student_json)
print("\nConverted Python object & detail:")
print("------------------------------")
student_python = Student.create_from_json(student_json)
print(student_python)
print("student_id:", student_python.student_id)
print("department:", student_python.department)
print("name:", student_python.name)
print("email:", student_python.email)
Output
Json object read from file: ------------------------------ { "student_id": "BCE001", "department": "Civil", "name": "Anisha Dahal", "email": "anisha@email.com" } Converted Python object & detail: ------------------------------ <Student Anisha Dahal> student_id: BCE001 department: Civil name: Anisha Dahal email: anisha@email.com
Non-nested & Multiple Object
Suppose you have following JSON data with multiple objects in file named student.json
:
[ { "student_id": "BCE001", "department": "Civil", "name": "Anisha Dahal", "email": "anisha@email.com" }, { "student_id": "BEL002", "department": "Electrical", "name": "Manisha Adhikari", "email": "manisha@email.com" }, { "student_id": "BEX003", "department": "Electronics", "name": "Sreeja Poudel", "email": "sreeja@email.com" }, { "student_id": "BCT004", "department": "Computer", "name": "Srishaa Sundas", "email": "srishaa@email.com" } ]
Python Source Code
import json
class Student:
def __init__(self,student_id, department, name, email):
self.student_id = student_id
self.department = department
self.name = name
self.email = email
@staticmethod
def create_from_json(data):
json_dictionary = json.loads(data)
return Student(**json_dictionary)
def __str__(self):
return "<Student {0}>".format(self.name)
# Test
student_python = []
with open("student.json", "r") as json_data:
student_json = json.loads(json_data.read())
for student in student_json:
student_python.append(Student(**student))
# Displaying student from python object
for student in student_python:
print('Python Object:', student)
Output
Python Object: <Student Anisha Dahal> Python Object: <Student Manisha Adhikari> Python Object: <Student Sreeja Poudel> Python Object: <Student Srishaa Sundas>
Nested & Multiple Object
Suppose you have following Nested JSON data in file named nested_student.json
:
[ { "student_id": "BCE001", "department": "Civil", "name": { "first": "Anisha", "last": "Dahal" }, "email": "anisha@email.com" }, { "student_id": "BCE002", "department": "Electrical", "name": { "first": "Manisha", "last": "Adhikari" }, "email": "manisha@email.com" }, { "student_id": "BCE003", "department": "Electronics", "name": { "first": "Sreeja", "last": "Poudel" }, "email": "sreeja@email.com" }, { "student_id": "BCE004", "department": "Computer", "name": { "first": "Srishaa", "last": "Sundas" }, "email": "srishaa@email.com" } ]
Python Source Code
import json
class Student:
def __init__(self,student_id, department, name, email):
self.student_id = student_id
self.department = department
self.first_name = name['first']
self.last_name = name['last']
self.email = email
@staticmethod
def create_from_json(data):
json_dictionary = json.loads(data)
return Student(**json_dictionary)
def __str__(self):
return "<Student {0}>".format(self.first_name)
# Test
student_python = []
with open("nested_student.json", "r") as json_data:
student_json = json.loads(json_data.read())
for student in student_json:
student_python.append(Student(**student))
# Displaying student from python object
print("\n\nAll student python objects")
print("------------------------------")
for student in student_python:
print('Python Object:', student)
# Detail of first student
print("\n\nDetail of first student")
print("------------------------------")
print("student_id:", student_python[0].student_id)
print("department:", student_python[0].department)
print("first name:", student_python[0].first_name)
print("last name:", student_python[0].last_name)
print("email:", student_python[0].email)
Output
All student python objects ------------------------------ Python Object: <Student Anisha> Python Object: <Student Manisha> Python Object: <Student Sreeja> Python Object: <Student Srishaa> Detail of first student ------------------------------ student_id: BCE001 department: Civil first name: Anisha last name: Dahal email: anisha@email.com
Using @classmethod
If you're using @classmethod
decorator then function definition for create_from_json()
will be:
@classmethod
def create_from_json(cls,data):
json_dictionary = json.loads(data)
return cls(**json_dictionary)