jsonbp


Namejsonbp JSON
Version 1.0.2 PyPI version JSON
download
home_page
SummarySchema based JSON Parser/Serializer
upload_time2023-09-24 23:33:47
maintainer
docs_urlNone
author
requires_python>=3.6
licenseMIT
keywords json serialization deserialization
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            
# jsonbp

**jsonbp** (JSON BluePrint) is a library to validate and deserialize JSON into
Python data based on a schema. There is [json-schema][json_schema] and its
implementations already if you want a more mature and more widely used technique,
but I needed some features that were not easily available by just patching
json-schema, so this library is the result.

jsonbp's design main goals were:
- schema reuse through import / type system
- support for enums
- built in numeric fixed precision type (which deserializes directly into Python's Decimal)
- built in datetime type (which deserializes directly into Python's datetime)
- error reporting with support for localization
- easy to integrate and use

## Contents
 - [Schema definition](#schema-definition)
 - [Usage](#usage)
 - [Requirements and Dependencies](#requirements-and-dependencies)
 - [Installation](#installation)
 - [Documentation](#documentation)

## Schema definition

jsonbp uses its own (very simple) domain language to define a schema.
The only mandatory declaration is the **"root"** entry, which determines the expected
JSON contents. Here's a simple hypothetical example:

```
root {
  x: float (min=0.0),
  y: float (min=0.0, max=1.0),
  
  optional color: {
    RED,
    GOLD,
    GREEN
  }
} [minLength=2]
```

This defines a schema that represents an array of minimum length 2 whose
elements contain the fields 'x' and 'y' (where both 'x' and 'y' are not
allowed to be negative and 'y' is not allowed to be greater than 1.0) and
an optional field 'color' that can be either "RED", "GOLD" or "GREEN".
A JSON instance that obeys this schema is:

```js
[
  {
    "x": 2.0,
    "y", 0.004,
    "color": "RED"
  },
  
  {
    "x": 3.0,
    "y", 0.009
  },
  
  {
    "x": 4.0,
    "y", 0.016,
    "color": "GREEN"
  }
]
```

Besides **"root"**, in jsonbp the following optional directives can be used to organize a schema:
- **"type"** -> to define specialized (restricted) simple types
- **"node"** -> to specify the contents of compound types (Objetcs)
- **"enum"** -> to define a list of allowed values for given fields
- **"import"** -> to reuse directives from existing blueprints

One can then make use of these features to simplify and make the schema more
modular. In the above example schema, we could split the definitions and get
something more reusable, like the following:

```
type non_negative : float (min=0.0)
type normalized : non_negative (max=1.0)

node coordinates {
  x: non_negative,
  y: normalized
}

include "color.jbp"
node colored_coordinates extends coordinates {
  optional color: color
}

root colored_coordinates[minLength=2]
```

where the contents of file "color.jbp" would then be:

```
enum color {
  RED,
  GOLD,
  GREEN
}
```

(For detailed information using these directives, see the [Documentation section](#documentation))

## Usage

All of jsonbp can be summarized in 2 functionalities:

### Schema parsing

- jsonbp.load(\<schema file path>) => \<blueprint object>
- jsonbp.loads(\<schema string>) => \<blueprint object>

These functions are used for schema/blueprint loading.
Both do the same thing, the only difference is that the former expects a path to a file
storing the schema content while the latter expects a string with the schema content itself.
When there's a problem with the supplied schema, an exception is thrown. More on this can
be read on [`Error handling and error localization`](docs/error.md). These functions, when
succeed loading the schema, return a blueprint instance that can then be used to deserialize
JSON strings.

When loading a file, the blueprint is stored in a cache and associated with the absolute
path of that file. Thus, loading the same file twice won't make jsonbp parse it a second
time. To force the parsing of posterior calls to *load()*, call *jsonbp.invalidateCache()*.

### JSON deserialization

- \<blueprint object>.deserialize(\<JSON string>) => (success, outcome)

This is the only method that is intended to be invoked from the blueprint object returned
by *load()*/*loads()*. It expects a string holding the JSON contents to be deserialized. It
returns a tuple in the form **(success, outcome)**. **success** being a boolean signalizing if
the deserialization was successful or not. If successful, **outcome** will hold the Python data
obtained from the JSON string. Otherwise (**success** is false) **outcome** will have a
message explaining what was not compliant according to the schema.

### Example

Here's how one uses these functions in code:

```py
import jsonbp

blueprint = jsonbp.loads('''
root {
  success: {
    YES,
    NO
  }
}
''')

jsonInstance = '{ "success": "YES" }'
success, outcome = blueprint.deserialize(jsonInstance)
print(f'Success: {success}')
print(f'Outcome: {outcome}')
```

## Requirements and Dependencies

jsonbp requires Python 3.6+, that's it.  
Under the hood, jsonbp uses [PLY][ply] for its schema parsing. PLY comes
included with jsonbp already, there's no need to download it separately.

## Installation

jsonbp is available at PyPI:  [https://pypi.org/project/jsonbp/](https://pypi.org/project/jsonbp/)

To install through pip:
```bash
pip install jsonbp
```

## Documentation

That was just an introduction, if you are interested in using jsonbp here are some more detailed information:
- [`Schema definition`](docs/schema.md)
- [`Error handling and error localization`](docs/error.md)
- [`Sample of using jsonbp in Flask`](https://github.com/vottini/sample-jsonbp-flask)

[//]: References
   [json_schema]: <https://json-schema.org/>
   [ply]: <https://www.dabeaz.com/ply/>
   

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "jsonbp",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": "",
    "keywords": "JSON,serialization,deserialization",
    "author": "",
    "author_email": "Gustavo Venturini <gustavo.c.venturini@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/22/60/8eb3db73cab4607e1fb0e5e9ca57d7f8a5f394216fe076ccbd4f50a79049/jsonbp-1.0.2.tar.gz",
    "platform": null,
    "description": "\n# jsonbp\n\n**jsonbp** (JSON BluePrint) is a library to validate and deserialize JSON into\nPython data based on a schema. There is [json-schema][json_schema] and its\nimplementations already if you want a more mature and more widely used technique,\nbut I needed some features that were not easily available by just patching\njson-schema, so this library is the result.\n\njsonbp's design main goals were:\n- schema reuse through import / type system\n- support for enums\n- built in numeric fixed precision type (which deserializes directly into Python's Decimal)\n- built in datetime type (which deserializes directly into Python's datetime)\n- error reporting with support for localization\n- easy to integrate and use\n\n## Contents\n - [Schema definition](#schema-definition)\n - [Usage](#usage)\n - [Requirements and Dependencies](#requirements-and-dependencies)\n - [Installation](#installation)\n - [Documentation](#documentation)\n\n## Schema definition\n\njsonbp uses its own (very simple) domain language to define a schema.\nThe only mandatory declaration is the **\"root\"** entry, which determines the expected\nJSON contents. Here's a simple hypothetical example:\n\n```\nroot {\n  x: float (min=0.0),\n  y: float (min=0.0, max=1.0),\n  \n  optional color: {\n    RED,\n    GOLD,\n    GREEN\n  }\n} [minLength=2]\n```\n\nThis defines a schema that represents an array of minimum length 2 whose\nelements contain the fields 'x' and 'y' (where both 'x' and 'y' are not\nallowed to be negative and 'y' is not allowed to be greater than 1.0) and\nan optional field 'color' that can be either \"RED\", \"GOLD\" or \"GREEN\".\nA JSON instance that obeys this schema is:\n\n```js\n[\n  {\n    \"x\": 2.0,\n    \"y\", 0.004,\n    \"color\": \"RED\"\n  },\n  \n  {\n    \"x\": 3.0,\n    \"y\", 0.009\n  },\n  \n  {\n    \"x\": 4.0,\n    \"y\", 0.016,\n    \"color\": \"GREEN\"\n  }\n]\n```\n\nBesides **\"root\"**, in jsonbp the following optional directives can be used to organize a schema:\n- **\"type\"** -> to define specialized (restricted) simple types\n- **\"node\"** -> to specify the contents of compound types (Objetcs)\n- **\"enum\"** -> to define a list of allowed values for given fields\n- **\"import\"** -> to reuse directives from existing blueprints\n\nOne can then make use of these features to simplify and make the schema more\nmodular. In the above example schema, we could split the definitions and get\nsomething more reusable, like the following:\n\n```\ntype non_negative : float (min=0.0)\ntype normalized : non_negative (max=1.0)\n\nnode coordinates {\n  x: non_negative,\n  y: normalized\n}\n\ninclude \"color.jbp\"\nnode colored_coordinates extends coordinates {\n  optional color: color\n}\n\nroot colored_coordinates[minLength=2]\n```\n\nwhere the contents of file \"color.jbp\" would then be:\n\n```\nenum color {\n  RED,\n  GOLD,\n  GREEN\n}\n```\n\n(For detailed information using these directives, see the [Documentation section](#documentation))\n\n## Usage\n\nAll of jsonbp can be summarized in 2 functionalities:\n\n### Schema parsing\n\n- jsonbp.load(\\<schema file path>) => \\<blueprint object>\n- jsonbp.loads(\\<schema string>) => \\<blueprint object>\n\nThese functions are used for schema/blueprint loading.\nBoth do the same thing, the only difference is that the former expects a path to a file\nstoring the schema content while the latter expects a string with the schema content itself.\nWhen there's a problem with the supplied schema, an exception is thrown. More on this can\nbe read on [`Error handling and error localization`](docs/error.md). These functions, when\nsucceed loading the schema, return a blueprint instance that can then be used to deserialize\nJSON strings.\n\nWhen loading a file, the blueprint is stored in a cache and associated with the absolute\npath of that file. Thus, loading the same file twice won't make jsonbp parse it a second\ntime. To force the parsing of posterior calls to *load()*, call *jsonbp.invalidateCache()*.\n\n### JSON deserialization\n\n- \\<blueprint object>.deserialize(\\<JSON string>) => (success, outcome)\n\nThis is the only method that is intended to be invoked from the blueprint object returned\nby *load()*/*loads()*. It expects a string holding the JSON contents to be deserialized. It\nreturns a tuple in the form **(success, outcome)**. **success** being a boolean signalizing if\nthe deserialization was successful or not. If successful, **outcome** will hold the Python data\nobtained from the JSON string. Otherwise (**success** is false) **outcome** will have a\nmessage explaining what was not compliant according to the schema.\n\n### Example\n\nHere's how one uses these functions in code:\n\n```py\nimport jsonbp\n\nblueprint = jsonbp.loads('''\nroot {\n  success: {\n    YES,\n    NO\n  }\n}\n''')\n\njsonInstance = '{ \"success\": \"YES\" }'\nsuccess, outcome = blueprint.deserialize(jsonInstance)\nprint(f'Success: {success}')\nprint(f'Outcome: {outcome}')\n```\n\n## Requirements and Dependencies\n\njsonbp requires Python 3.6+, that's it.  \nUnder the hood, jsonbp uses [PLY][ply] for its schema parsing. PLY comes\nincluded with jsonbp already, there's no need to download it separately.\n\n## Installation\n\njsonbp is available at PyPI:  [https://pypi.org/project/jsonbp/](https://pypi.org/project/jsonbp/)\n\nTo install through pip:\n```bash\npip install jsonbp\n```\n\n## Documentation\n\nThat was just an introduction, if you are interested in using jsonbp here are some more detailed information:\n- [`Schema definition`](docs/schema.md)\n- [`Error handling and error localization`](docs/error.md)\n- [`Sample of using jsonbp in Flask`](https://github.com/vottini/sample-jsonbp-flask)\n\n[//]: References\n   [json_schema]: <https://json-schema.org/>\n   [ply]: <https://www.dabeaz.com/ply/>\n   \n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Schema based JSON Parser/Serializer",
    "version": "1.0.2",
    "project_urls": {
        "Homepage": "https://github.com/vottini/jsonbp"
    },
    "split_keywords": [
        "json",
        "serialization",
        "deserialization"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a85117d71653ec34e490ed9549ed68b1bf7b52962a2a7330bf4e4d3ee71a54e4",
                "md5": "0fb88c6a7355d445168616cd451f063b",
                "sha256": "02d1c104a39f4524aa90ae39cdb510cd219c19837ab4ef1a71cd624d7b3f59a4"
            },
            "downloads": -1,
            "filename": "jsonbp-1.0.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "0fb88c6a7355d445168616cd451f063b",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 53047,
            "upload_time": "2023-09-24T23:33:45",
            "upload_time_iso_8601": "2023-09-24T23:33:45.336991Z",
            "url": "https://files.pythonhosted.org/packages/a8/51/17d71653ec34e490ed9549ed68b1bf7b52962a2a7330bf4e4d3ee71a54e4/jsonbp-1.0.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "22608eb3db73cab4607e1fb0e5e9ca57d7f8a5f394216fe076ccbd4f50a79049",
                "md5": "27c0779b86cf662c010c6b78077e759e",
                "sha256": "d4454da836b03a99bd2c29664f40ae0fe949710c17319e85de606663ec3a9118"
            },
            "downloads": -1,
            "filename": "jsonbp-1.0.2.tar.gz",
            "has_sig": false,
            "md5_digest": "27c0779b86cf662c010c6b78077e759e",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 53224,
            "upload_time": "2023-09-24T23:33:47",
            "upload_time_iso_8601": "2023-09-24T23:33:47.591018Z",
            "url": "https://files.pythonhosted.org/packages/22/60/8eb3db73cab4607e1fb0e5e9ca57d7f8a5f394216fe076ccbd4f50a79049/jsonbp-1.0.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-09-24 23:33:47",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "vottini",
    "github_project": "jsonbp",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "jsonbp"
}
        
Elapsed time: 0.11453s