In this post 3 examples how to convert Python objects to JSON:
- Python convert class object to json(non built-in)
- s = json.dumps(person.dict)
- Python convert object to JSON string(with validation)
- def serialize(obj)
- Python convert list object to JSON file
- json.dump(dt, file)
If you want to convert to JSON object of a class that is not part of built-in types in Python you can end with error:
TypeError with "is not JSON serializable"
In this case you have several options.
you can check also:
Python convert class object to json(non built-in)
The easiest way to work around the error is by simply adding __dict__
to dumps method:
import json
class Person(object):
def __init__(self):
self.name = 'John'
self.age = 25
self.id = 1
person = Person()
s = json.dumps(person.__dict__)
print(s)
result:
{"id": 1, "age": 25, "name": "John"}
- import the JSON module
- declaring a new Person class
- creating a new instance of this class
- dumping the object with option:
__dict__
- otherwise error will be raised
Python convert object to JSON string(with validation)
Method for JSON serializing of objects which are not serializable by default dumps method. The advantage is that you can check the object and treat it in best way for its type:
import json
from datetime import date
class Person(object):
def __init__(self):Python save objects as json file
self.name = 'John'
self.age = 25
self.id = 1
person = Person()
def serialize(obj):
if isinstance(obj, date):
serial = obj.isoformat()
return serial
return obj.__dict__
print(serialize(person))
result:
{"id": 1, "age": 25, "name": "John"}
- we are importing the required modules
- declaring a new Person class
- creating a new instance of this class
- custom method which check is it serializable or not and return appropriate value.
Python convert list object to JSON file
Saving a python object to JSON file is very easy too:
import json
class Person(object):
def __init__(self):
self.name = 'John'
self.age = 25
self.id = 1
person = Person()
#save to file
dt = {}
dt.update(vars(person))
with open("/home/test/person.txt", "w") as file:
json.dump(dt, file)
result:
/home/test/person.txt
{"id": 1, "age": 25, "name": "John"}
If you want to save list of objects with Python to JSON you can do it by:
json_string = json.dumps([ob.__dict__ for ob in list_objects])
if you deal with non serializble objects then you can simply do:
def obj_to_dict(obj):
return obj.__dict__
json_string = json.dumps(list_objects, default=obj_to_dict)
where list_objects is the list with your objects.
P.S. Code example which was asked in comment section below or full example how can you serialize not serializable classes:
import json
class error:
def __init__(self):
self.errorCode="server issue"
self.errorMessage="201"
class BaseRespone():
def __init__(self):
self.success = "data fetch successfully"
self.data={"succss":"msg"}
self.error1 = error()
def obj_to_dict(obj):
return obj.__dict__
bs = BaseRespone()
json_string = json.dumps(bs.__dict__, default = obj_to_dict)
json_string1 = json.loads(json_string)