Here is a simple solution for a simple feature:
.toJSON() Method
Instead of a JSON serializable class, implement a serializer method:
import json
class Object:
def toJSON(self):
return json.dumps(
self,
default=lambda o: o.__dict__,
sort_keys=True,
indent=4)
So you just call it to serialize:
me = Object()
me.name = "Onur"
me.age = 35
me.dog = Object()
me.dog.name = "Apollo"
print(me.toJSON())
will output:
{
"age": 35,
"dog": {
"name": "Apollo"
},
"name": "Onur"
}
For a fully-featured library, you can use orjson.
Answer from Onur Yıldırım on Stack OverflowHere is a simple solution for a simple feature:
.toJSON() Method
Instead of a JSON serializable class, implement a serializer method:
import json
class Object:
def toJSON(self):
return json.dumps(
self,
default=lambda o: o.__dict__,
sort_keys=True,
indent=4)
So you just call it to serialize:
me = Object()
me.name = "Onur"
me.age = 35
me.dog = Object()
me.dog.name = "Apollo"
print(me.toJSON())
will output:
{
"age": 35,
"dog": {
"name": "Apollo"
},
"name": "Onur"
}
For a fully-featured library, you can use orjson.
Do you have an idea about the expected output? For example, will this do?
>>> f = FileItem("/foo/bar")
>>> magic(f)
'{"fname": "/foo/bar"}'
In that case you can merely call json.dumps(f.__dict__).
If you want more customized output then you will have to subclass JSONEncoder and implement your own custom serialization.
For a trivial example, see below.
>>> from json import JSONEncoder
>>> class MyEncoder(JSONEncoder):
def default(self, o):
return o.__dict__
>>> MyEncoder().encode(f)
'{"fname": "/foo/bar"}'
Then you pass this class into the json.dumps() method as cls kwarg:
json.dumps(cls=MyEncoder)
If you also want to decode then you'll have to supply a custom object_hook to the JSONDecoder class. For example:
>>> def from_json(json_object):
if 'fname' in json_object:
return FileItem(json_object['fname'])
>>> f = JSONDecoder(object_hook = from_json).decode('{"fname": "/foo/bar"}')
>>> f
<__main__.FileItem object at 0x9337fac>
>>>
JSON Serialization
Introduce a __json__ magic method - Ideas - Discussions on Python.org
Problems getting url. TypeError: Object of type Series is not JSON serializable
Why are python dataclasses not JSON serializable?
I have been using more and more of Python over the past few weeks because I got sick of JS. When I asked a programmer friend of mine who uses JS religiously what he thought about using Python for web backends, he told me that it would be slow because of JSON serialization.
I spent some time researching this, but couldn’t find anything decisive that explained why JSON serialization would be faster in JS. The answers I found said a few things:
-
V8 is optimized for this because it’s part of the JS standard
-
it’s slow in Python because of an implementation of how the JSON to Python representation (JSON dump) function is represented in Python.
Does anyone else have any further insight on this topic? I am trying to understand this at a fundamental level and cut through any noise / wrong understanding.
Thanks so much!