Last week I made a little library called json-schema-reducer. It's a simple function that takes a JSON Schema and dict (or a JSON string or a .json file path), and makes a new dict that only contains the keys listed in the JSON Schema.
This is handy if you have a JSON Schema which dictates what you can/want to share/publish/save, but you have a data structure that contains keys and values you don't want to share/publish/save.
I built this because there are a couple of projects that can turn data structures into models from a JSON Schema but none that have the ability to reduce stuff from a data structure. Here's an example:
Sample JSON Schema (schema.json)
{
"type": "object",
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Sample JSON Schema",
"required": [
"name",
"sex"
],
"properties": {
"name": {
"type": "string"
},
"sex": {
"type": "string"
}
"title": {
"type": "string"
}
}
}
Sample data structure (sample.json)
{
"name": "Peter",
"sex": "male",
"email": "peterbe@example.com",
}
Usage
>>> from json_schema_reducer import make_reduced_dict
>>> make_reduced_dict('schema.json', 'sample.json')
{'name': 'Peter', 'sex': 'male'} # Note! No "email" key
The project works in Python 2 and Python 3. See tests.
Also, the function tries to be convenient in that it can accept either a dict, a JSON string or path to a .json file.
Comments