Provides json unmarshalling to strict types for Python. This ensures you always get safe dictionaries for usage. This allows you to always do the below without worrying about KeyErrors.
schema = JSONObject(...)
json_parsed = schema.loads(json_unparsed)
json_parsed['my_key']['my_next_key']
Currently supports basic Python primitives: str
, list
, dict
, float
, int
, bool
Coming soon: Python DateTime support
First, start by declaring your schema of objects you expect to get. For example, if I expect to get a user representation,
user_schema = JSONObject({
username: str,
id: int,
name: str,
active: bool,
permissions: [
{
'resource': 'string',
'action': 'string',
}
]
})
# Make the relevant API call...
req = requests.get('...')
data = user_schema.loads(req.json()) # The loads signature is indifferent between json.loads(s) and s itself.
# You can now do things like
for perm in data['permissions']:
print(perm['resource'])
# safely without worrying about KeyErrors
from json_obj import JSONObject
>>> schema = {
'a': str,
'b': int,
'c': float,
'd': boolean,
}
>>> loader = JSONObject(schema)
>>> loader.loads({
'a': 34,
'b': True,
})
{
'a': '34',
'b': 1,
'c': 0.0,
'd': False,
}