A simple, yet powerful, JSON/python dictionary to object deserialization
Project description
python-easy-json: simple, yet powerful, JSON/python dictionary to object deserialization
python-easy-json is a recursive JSON to python object deserializer with support for defining data models and casting data to python using type hint annotations.
The python-easy-json JSONObject class can be used to:
Deserialize: Recursively convert a JSON string or python dictionary to a python object
Serialize: Export the object data to a JSON string or python dictionary
Type Hinting Integration: Convert JSON values to specific types by creating models and type hints.
Define Data Models: Create simple, yet powerful data models for working with data from any source
IDE Auto Completion: IDEs with auto-completion and support python type hinting will auto-complete model properties
Get It Now
$ pip install python-easy-json
Why a another JSON to Object library?
After years of python development, I grew tired of receiving data from APIs, database, csv files and so on and working with them as python dictionaries. The “simple” JSON deserializer library options I saw really didn’t fit how easy I felt that deserializing to a JSON object should be. Additionally, I wanted to create simple data model classes and using python “Type Hinting” to define property value types.
Simple Examples
Just pass a JSON string or python dict argument to the JSONObject constructor. In this example, we can switch from using dict key lookups to an array of JSONObjects.
for row in results: if row['the_key'][0]['another_key'] == 'the_value': ...
With JSONObject this may be re-written as below, using list comprehension. This makes the code more readable and less cluttered when working with complex dictionary structures in code.
from python_easy_json import JSONObject for row in [JSONObject(r) for r in results]: if row.the_key[0].another_key == 'the_value': ...
Data from a JSON String
from python_easy_json import JSONObject # JSON string obj = JSONObject('{"test_key": "test_value"}') print(obj.to_json()) {"test_key": "test_value"}
Data from a python dictionary
# Python dictionary obj = JSONObject({'test_key': 'test_value'}) print(obj.to_json()) {"test_key": "test_value"}
Data Models For Anything
Using the python-easy-json JSONObject class, you can create data models, including deeply nested models and arrays, from any JSON string or dictionary. Additionally, python “Type Hints” may be used to cast values to the type defined by the type hint annotations.
As a bonus; IDEs with auto-completion and support for python type hinting will auto-complete model properties as you type.
This example shows how to define nested/child data models, including lists of nested data models.
# Represents json from 'tests/test_data/nested_data_1.json' class CakeToppingTypeModel(JSONObject): id: int = None type: str = None class CakeBatterTypeModel(JSONObject): id: int = None type: str = None class CakeBatterModel(JSONObject): batter: List[CakeBatterTypeModel] = None class CakeModel(JSONObject): id: str = None type: str = None name: str = None ppu: float = None batters: CakeBatterModel = None topping: List[CakeToppingTypeModel] cake = CakeModel(data) print(f'Cake: {cake.name} ({len(cake.batters.batter)} ingredents).') Cake: Devil's Food Cake (4 ingredients).
Type Hints Automatically Convert JSON Values
If a model has been defined and the properties have python Type Hint annotations, the JSONObject can convert values to the annotation types.
from datetime import datetime class TimestampModel(JSONObject): id: int = None timestamp: datetime = None data = {'id': "123", "timestamp": "2022-09-19 10:11:01.123456"} obj = TimestampModel(data, cast_types=True) if obj.id > 0: print(f"ID: {obj.id}: {obj.timestamp.strftime('%b %d, %Y @ %H:%M:%S %p')}") $ ID: 123: Sep 19, 2022 @ 10:11:01 AM
Documentation
JSONObject Class
JSONObject.__init__(data: Union[Dict, str, None] = None, cast_types: bool = False, ordered: bool = False) Load the dictionary or JSON string data argument into ourselves as properties. :param data: Dictionary or valid JSON string. :param cast_types: If properties of this class are type annotated, try to cast them. :param ordered: Use OrderedDict() if set, otherwise use dict(). For python <= 3.6. JSONObject.to_json(indent: int = None) Export stored data as a json string. :param indent: Positive integer value for formatting JSON string indenting. :returns: JSON string JSONObject.to_dict(recursive: bool = True, dates_to_str: bool = False) Export stored data as a python dictionary object. :param recursive: Boolean, recursively convert nested JSONObjects to a dict :param dates_to_str: Boolean, convert all date or datetime values to string. :returns: dictionary object JSONObject.update([Dict|List|Tuple]) accepts either a dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: obj.update(sky=1, cloud=2). Plus Operator: Two JSONObjects may be merged using the plus (+) operator: obj = obj + other_obj. Number of Properties: The number of managed properties may be determined by using the Python 'len()' function: len(obj) == 5.
Project Links
License
MIT licensed. See the bundled LICENSE <https://github.com/robabram/python-easy-json/blob/main/LICENSE> file for more details.
Unittest Data
Testing JSON data for examples and unittests sourced from: https://opensource.adobe.com/Spry/samples/data_region/JSONDataSetSample.html
Project details
Release history Release notifications | RSS feed
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
File details
Details for the file python_easy_json-1.2.0.tar.gz
.
File metadata
- Download URL: python_easy_json-1.2.0.tar.gz
- Upload date:
- Size: 17.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.12.4
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 964c5e1be1a3adcd1dd14e5ffb922ab708c2ec5471a28ba0949b3b5ff28fb8b6 |
|
MD5 | 0476b688e8a7c2773af029c676619e4c |
|
BLAKE2b-256 | fdd75982f24b5cacd68c19903f28c7d8dba679b151886fb9901def2db4a65fd7 |
File details
Details for the file python_easy_json-1.2.0-py3-none-any.whl
.
File metadata
- Download URL: python_easy_json-1.2.0-py3-none-any.whl
- Upload date:
- Size: 8.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.12.4
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 6ad5e7fae840e0019c2789283ca3005289cc74a0dc10bb651076f6e6abf8a3fc |
|
MD5 | 935d0dbc27ec2740d7a01893e2235275 |
|
BLAKE2b-256 | 9bd580200cf116782fc6af5218aaa9c1d0d7bab0ed9820943048f03f7e14090f |