Python JSON to Class Object
Python JSON to Class Object
To convert a Python JSON string to a Class Object, use the json.loads()
function in combination with a custom deserialization method. This allows mapping JSON keys to the attributes of a Python class.
For example, consider the following JSON string representing an object:
{"name": "John", "age": 30, "city": "New York"}
We can map this JSON to a Python class and access its attributes programmatically.
Examples
1. Convert JSON Object to Python Class Object
In this example, we will define a Python class and use json.loads()
with a custom method to deserialize JSON into a class object.
Python Program
import json
# Define a Python class
class Person:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
# Custom method to map JSON to class
def json_to_class(json_string):
data = json.loads(json_string)
return Person(**data)
# JSON string
json_string = '{"name": "John", "age": 30, "city": "New York"}'
# Convert JSON to class object
person = json_to_class(json_string)
# Access attributes
print(person.name)
print(person.age)
print(person.city)
Output
John
30
New York
2. Convert JSON Array to List of Class Objects
In this example, we will map a JSON array to a list of Python class objects.
Python Program
import json
# Define a Python class
class Person:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
# Custom method to map JSON to class
def json_to_class_list(json_string):
data = json.loads(json_string)
return [Person(**item) for item in data]
# JSON array
json_array = '[{"name": "John", "age": 30, "city": "New York"}, {"name": "Jane", "age": 25, "city": "Chicago"}]'
# Convert JSON to list of class objects
persons = json_to_class_list(json_array)
# Access attributes
for person in persons:
print(person.name, person.age, person.city)
Output
John 30 New York
Jane 25 Chicago
Summary
In this tutorial, we learned how to convert JSON strings into Python class objects using json.loads()
and custom deserialization methods. This approach helps in working with structured data in Python.