json-schema-reducer

02 August 2016   0 comments   Python

https://github.com/peterbe/json-schema-reducer

Powered by Fusion×

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

Thank you for posting a comment

Your email will never ever be published


Related posts

Previous:
Premailer 3.0.0 - classes kept by default 07 June 2016
Next:
How to identify/classify what language a piece of text is 09 August 2016
Related:
Cope with JSONDecodeError in requests.get().json() in Python 2 and 3 16 November 2016
Gzip rules the world of optimization, often 09 August 2014
Migration of Postgres 9.2 to 9.3 with Homebrew and json_enhancements 30 April 2014
From Postgres to JSON strings 12 November 2013
jsonpprint - a Python script to format JSON data nicely 21 November 2010
How I made my MongoDB based web app 10 times faster 21 October 2010
To JSON, Pickle or Marshal in Python 08 May 2009