Tools, FAQ, Tutorials:
Extending json.JSONEncoder Class
How to extend json.JSONEncoder class? I want to encode other Python data types to JSON.
✍: FYIcenter.com
If you encode your own data types to JSON strings,
you need to extend the json.JSONEncoder class and override the default()
function.
The following Python example shows you how to extend json.JSONEncoder class to encode "complex" data type into JSON format:
C:\fyicenter>type MyJSONEncoder.py
# MyJSONEncoder.py
# Copyright (c) FYIcenter.com
import json
class MyJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, complex):
return {'r': obj.real, 'i': obj.imag}
return json.JSONEncoder.default(self, obj)
encoder = MyJSONEncoder(indent=4)
i = 2
f = 2.1
c = 2 + 1j
o = {'int': i, 'float': f, 'complex': c}
j = encoder.encode(o)
print(j)
C:\fyicenter>python MyJSONEncoder.py
{
"int": 2,
"float": 2.1,
"complex": {
"r": 2.0,
"i": 1.0
}
}
⇒ json.loads() - Loading JSON into Object
⇐ What Is json.JSONEncoder Class
2018-10-08, ∼5082🔥, 0💬
Popular Posts:
How to create the Hello-3.0.epub package? I have all required files to create Hello-3.0.epub. To cre...
What is EPUB 3.0 Metadata "dc:publisher" and "dc:rights" elements? EPUB 3.0 Metadata "dc:publisher" ...
How To Create an Array with a Sequence of Integers or Characters in PHP? The quickest way to create ...
What is EPUB 3.0 Metadata "dc:publisher" and "dc:rights" elements? EPUB 3.0 Metadata "dc:publisher" ...
What Azure AD App Registration Manifest? Azure AD App Registration Manifest is JSON file that contai...