Python @dataclass <=> JSON declarable, interchangeable, validatable, sanitizable.
Project description
jsonclasses
Python dataclasses <=> JSON declarable, interchangeable, validatable, sanitizable.
Motivation
Python lacks a great solution of handling JSON web inputs, JSON objects manipulation and serialization. By declaring field specifications with extended feature set of @dataclass, we can solve this issue elegantly.
Installation
Install jsonclasses with pip.
pip install jsonclasses
Examples
Converting from json dict
To create a jsonclass object from json dict, just use its initialization method. Type transforming, input sanitization, and JSON key case convension are taken into consideration during this process.
from jsonclasses import jsonclass, JSONObject, types
@jsonclass
class Article(JSONObject):
title: str = types.str.maxlength(100).required
content: str = types.str.required
read_count: int = types.int.default(0).required
json_input = {
'title': 'Declarative Web API Development with jsonclasses',
'content': 'With jsonclasses, you can easily implement your web API with declaration style rather than procedural style.'
}
article = Article(**json_input)
# =>
# Article(
# title='Declarative Web API Development with jsonclasses',
# content='With jsonclasses, you can easily implement your web API with declaration style rather than procedural style.',
# read_count=0
# )
Coverting to json dict
To convert a jsonclass to json dict, use instance method tojson
. During this
process, Python data types are converted to JSON acceptable types.
from jsonclasses import jsonclass, JSONObject, types
@jsonclass
class MobilePhone(JSONObject):
name: str = types.str.maxlength(50).required,
model: str = types.str.oneof(['iphone', 'galaxy', 'pixel']).required,
year: int = types.int.range(2010, 2020).required
mobile_phone = MobilePhone(name='iPhone 12', model='iphone', year=2020)
mobile_phone.tojson()
# =>
# {'name': 'iPhone 12', 'model': 'iphone', 'year': 2020}
Sanitization
Jsonclass sanitizes inputs on initialization and set
. Values of extra fields
are just ignored. Fields marked with readonly
won't accept value inputs.
from jsonclasses import jsonclass, JSONObject, types
@jsonclass
class Coupon(JSONObject):
type: str = types.str.oneof(['spring', 'flash', 'limited']).required
discount_rate: float = types.float.range(0, 1).required
used: bool = types.bool.readonly.default(False).required
user_id: str = types.str.length(24).required
json_input = {
'type': 'flash',
'discount_rate': 0.3,
'used': True,
'user_id': '12345678901234567890abcd',
'haha': 'I want to hack into this system!'
}
Coupon(**json_input)
# =>
# Coupon(type='flash', discount_rate=0.3, used=False, user_id='12345678901234567890abcd')
# * value of field 'haha' is ignored.
# * value of 'used' is not affected by the fraud input.
Validation
from jsonclasses import jsonclass, JSONObject, types
@jsonclass
class UserProfile(JSONObject):
name: str = types.str.required
gender: str = types.str.oneof(['male', 'female'])
user_profile = UserProfile(name='John', gender='mlae')
user_profile.validate()
# =>
# jsonclasses.exceptions.ValidationException: Json classes validation failed:
# 'gender': Value 'mlae' at 'gender' should be one of ['male', 'female'].
Integration with web frameworks
Using jsonclasses
with sanic
web framework.
Using jsonclasses
with flask
web framework.
Supported Python versions
jsonclasses
supports Python >= 3.7
.
License
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
Hashes for jsonclasses-0.4.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | b6c7ba85ca706fed993a2c686da9f24d7bdb96b638fec43f8211b0eb09e01786 |
|
MD5 | c571f4abadfe15ab8d068a87c3ac94e6 |
|
BLAKE2b-256 | b6f99ddd0441737db5d6befb00bb86f5e94d5005fdf001452714ddb3885d92e3 |