JSON Tools Library
Project description
JSON related tools
Infer Schema
With function infer_schema
, you can get schema from json object. The output complys to JSON Schema Specification. Here is an example:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from json_tools2 import infer_schema
import json
def main():
schema = infer_schema({"foo": 1})
print(json.dumps(schema, indent=4))
if __name__ == '__main__':
main()
Output
{
"type": "object",
"properties": {
"foo": {
"type": "integer"
}
}
}
When you have an array of element from different types, or object with the same property but from different type, we need to merge schema.
case 1: "a"
and 2
are of different types and we need to merge schema
["a", 2]
case 2: "a"
and 2
are of different types and we need to merge schema
[{"foo": "a"}, {"foo": 2}]
Following rules applies when we do schema merging:
- For
null
, any type can merged to it and return anullable type
, for example,sting
merge tonull
and return anullable string
- For
string
, onlynull
can merged tostring
and returnnullable string
. - For
number
, followings are the only valid type that can merge to itinteger
can merged to it without changing itnull
can merge to it and becomenullable number
- For
integer
, followings are the only valid type that can merge to itnumber
can merged to it and upgrade it tonumber
null
can merge to it and becomenullable number
- For
boolean
, followings are the only valid type that can merge to itnull
can merge to it and becomenullable boolean
- For
object
, followings are the only valid type that can merge to itnull
can merge to it and becomenullable object
- For
array
, followings are the only valid type that can merge to itnull
can merge to it and becomenullable array
We use anyOf
to represent nullable type
, for example:
This represent a nullable integer
type.
{
"anyOf": [{"type": "integer"},{"type": "null"}]
}
For any schema inferred, you should be able to validate the payload with the schema inferred, here is an example:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# You need to do "pip install jsonschema"
from json_tools2 import infer_schema
from jsonschema import validate
import json
def main():
payload = {"foo": 1}
schema = infer_schema(payload)
validate(instance=payload, schema=schema) # it should not throw exception
if __name__ == '__main__':
main()
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 json_tools2-0.0.7-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 4b76373042606c7ba586fd56f337abd89d959b92befd698fc07bf8682633492c |
|
MD5 | e9678064e1691e2e6be3d69670585497 |
|
BLAKE2b-256 | 7f5ccb12a49b5792b9950e390e00bc756c1513a59a50d34ccecb6c8722ab34ee |