Easily extend JSON to encode and decode arbitrary Python objects.
Project description
extendedjson
Easily extend JSON to encode and decode arbitrary Python objects.
Getting started
You can get extendedjson
from PyPI,
which means it's easily installable with pip
:
python -m pip install extendedjson
Example usage
Suppose you want to extend the JSON format to handle complex numbers,
which corresponds to the type complex
in Python.
To do that, you need to:
- Determine how a complex number could look like as a JSON dictionary.
For example, a dictionary with keys
"real"
and"imag"
is enough to determine what complex number we are talking about. - Subclass
ExtendedEncoder
and implement the methodencode_complex
that accepts a complex number and returns a dictionary with the format you defined. - Subclass
ExtendedDecoder
and implement a methoddecode_complex
that accepts a dictionary with the format you described and returns an instance of acomplex
number.
Here is the code:
import extendedjson as xjson
class MyEncoder(xjson.ExtendedEncoder):
def encode_complex(self, c):
return {"real": c.real, "imag": c.imag}
class MyDecoder(xjson.ExtendedDecoder):
def decode_complex(self, dict_):
return complex(dict_["real"], dict_["imag"])
Then, you can use your classes with the standard module json
,
by specifying the cls
keyword argument in the functions json.load
, json.loads
, json.dump
, and json.dumps
:
import json
c = complex(1, 2)
c_json = json.dumps(c, cls=MyEncoder)
c_ = json.loads(c_json, cls=MyDecoder)
print(c_) # (1+2j)
print(c_ == c) # True
Refer to this article to learn more about the internal details of extendedjson
.
Changelog
Refer to the CHANGELOG.md file.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for extendedjson-0.1.3-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 6e16a9528f826c19fa0ad1d0188ba3c9c31d52fd683d3a39a1d06b4b53d25c3e |
|
MD5 | b98846ed90ca45c52c68b2ca8ff6f3a4 |
|
BLAKE2b-256 | a9efc2cb4fa9f850b18c10736236bf604becbfd8130a76f8bfc4a82ae988a17f |