marshmallow-jsonschema


Namemarshmallow-jsonschema JSON
Version 0.13.0 PyPI version JSON
download
home_pagehttps://github.com/fuhrysteve/marshmallow-jsonschema
SummaryJSON Schema Draft v7 (http://json-schema.org/) formatting with marshmallow
upload_time2021-10-21 18:02:40
maintainer
docs_urlNone
authorStephen Fuhry
requires_python>=3.6
licenseMIT License
keywords marshmallow-jsonschema marshmallow schema serialization jsonschema validation
VCS
bugtrack_url
requirements marshmallow
Travis-CI No Travis.
coveralls test coverage
            ## marshmallow-jsonschema: JSON Schema formatting with marshmallow

![Build Status](https://github.com/fuhrysteve/marshmallow-jsonschema/workflows/build/badge.svg)
[![Coverage Status](https://coveralls.io/repos/github/fuhrysteve/marshmallow-jsonschema/badge.svg?branch=master)](https://coveralls.io/github/fuhrysteve/marshmallow-jsonschema?branch=master)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/python/black)

 marshmallow-jsonschema translates marshmallow schemas into
 JSON Schema Draft v7 compliant jsonschema. See http://json-schema.org/

#### Why would I want my schema translated to JSON?

What are the use cases for this? Let's say you have a
marshmallow schema in python, but you want to render your
schema as a form in another system (for example: a web browser
or mobile device).

#### Installation

Requires python>=3.6 and marshmallow>=3.11. (For python 2 & marshmallow 2 support, please use marshmallow-jsonschema<0.11)

```
pip install marshmallow-jsonschema
```

#### Some Client tools can render forms using JSON Schema

* [react-jsonschema-form](https://github.com/mozilla-services/react-jsonschema-form) (recommended)
  * See below extension for this excellent library!
* https://github.com/brutusin/json-forms
* https://github.com/jdorn/json-editor
* https://github.com/ulion/jsonform

### Examples

#### Simple Example

```python
from marshmallow import Schema, fields
from marshmallow_jsonschema import JSONSchema

class UserSchema(Schema):
    username = fields.String()
    age = fields.Integer()
    birthday = fields.Date()

user_schema = UserSchema()

json_schema = JSONSchema()
json_schema.dump(user_schema)
```

Yields:

```python
{'properties': {'age': {'format': 'integer',
                        'title': 'age',
                        'type': 'number'},
                'birthday': {'format': 'date',
                             'title': 'birthday',
                             'type': 'string'},
                'username': {'title': 'username', 'type': 'string'}},
 'required': [],
 'type': 'object'}
```

#### Nested Example

```python
from marshmallow import Schema, fields
from marshmallow_jsonschema import JSONSchema
from tests import UserSchema


class Athlete(object):
    user_schema = UserSchema()

    def __init__(self):
        self.name = 'sam'


class AthleteSchema(Schema):
    user_schema = fields.Nested(JSONSchema)
    name = fields.String()

    
athlete = Athlete()
athlete_schema = AthleteSchema()

athlete_schema.dump(athlete)
```

#### Complete example Flask application using brutisin/json-forms

![Screenshot](http://i.imgur.com/jJv1wFk.png)

This example renders a form not dissimilar to how [wtforms](https://github.com/wtforms/wtforms) might render a form.

However rather than rendering the form in python, the JSON Schema is rendered using the
javascript library [brutusin/json-forms](https://github.com/brutusin/json-forms).


```python
from flask import Flask, jsonify
from marshmallow import Schema, fields
from marshmallow_jsonschema import JSONSchema

app = Flask(__name__)


class UserSchema(Schema):
    name = fields.String()
    address = fields.String()


@app.route('/schema')
def schema():
    schema = UserSchema()
    return jsonify(JSONSchema().dump(schema))


@app.route('/')
def home():
    return '''<!DOCTYPE html>
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/brutusin.json-forms/1.3.0/css/brutusin-json-forms.css"><Paste>
<script src="https://code.jquery.com/jquery-1.12.1.min.js" integrity="sha256-I1nTg78tSrZev3kjvfdM5A5Ak/blglGzlaZANLPDl3I=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.min.js"></script>
<script src="https://cdn.jsdelivr.net/brutusin.json-forms/1.3.0/js/brutusin-json-forms.min.js"></script>
<script>
$(document).ready(function() {
    $.ajax({
        url: '/schema'
        , success: function(data) {
            var container = document.getElementById('myform');
            var BrutusinForms = brutusin["json-forms"];
            var bf = BrutusinForms.create(data);
            bf.render(container);
        }
    });
});
</script>
</head>
<body>
<div id="myform"></div>
</body>
</html>
'''


if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

```


### Advanced usage
#### Custom Type support

Simply add a `_jsonschema_type_mapping` method to your field
so we know how it ought to get serialized to JSON Schema.

A common use case for this is creating a dropdown menu using
enum (see Gender below).


```python
class Colour(fields.Field):

    def _jsonschema_type_mapping(self):
        return {
            'type': 'string',
        }

    def _serialize(self, value, attr, obj):
        r, g, b = value
        r = "%02X" % (r,)
        g = "%02X" % (g,)
        b = "%02X" % (b,)
        return '#' + r + g + b 

class Gender(fields.String):
    def _jsonschema_type_mapping(self):
        return {
            'type': 'string',
            'enum': ['Male', 'Female']
        }


class UserSchema(Schema):
    name = fields.String(required=True)
    favourite_colour = Colour()
    gender = Gender()

schema = UserSchema()
json_schema = JSONSchema()
json_schema.dump(schema)
```


### React-JSONSchema-Form Extension

[react-jsonschema-form](https://react-jsonschema-form.readthedocs.io/en/latest/)
is a library for rendering jsonschemas as a form using React. It is very powerful
and full featured.. the catch is that it requires a proprietary
[`uiSchema`](https://react-jsonschema-form.readthedocs.io/en/latest/form-customization/#the-uischema-object)
to provide advanced control how the form is rendered.
[Here's a live playground](https://rjsf-team.github.io/react-jsonschema-form/)

*(new in version 0.10.0)*

```python
from marshmallow_jsonschema.extensions import ReactJsonSchemaFormJSONSchema

class MySchema(Schema):
    first_name = fields.String(
        metadata={
            'ui:autofocus': True,
        }
    )
    last_name = fields.String()

    class Meta:
        react_uischema_extra = {
            'ui:order': [
                'first_name',
                'last_name',
            ]
        }


json_schema_obj = ReactJsonSchemaFormJSONSchema()
schema = MySchema()

# here's your jsonschema
data = json_schema_obj.dump(schema)

# ..and here's your uiSchema!
ui_schema_json = json_schema_obj.dump_uischema(schema)



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/fuhrysteve/marshmallow-jsonschema",
    "name": "marshmallow-jsonschema",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": "",
    "keywords": "marshmallow-jsonschema marshmallow schema serialization jsonschema validation",
    "author": "Stephen Fuhry",
    "author_email": "fuhrysteve@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/2f/53/109d80013b70b6140d05e521ad31e3014680007b51c3dfac72ad20a2d6ee/marshmallow-jsonschema-0.13.0.tar.gz",
    "platform": "",
    "description": "## marshmallow-jsonschema: JSON Schema formatting with marshmallow\n\n![Build Status](https://github.com/fuhrysteve/marshmallow-jsonschema/workflows/build/badge.svg)\n[![Coverage Status](https://coveralls.io/repos/github/fuhrysteve/marshmallow-jsonschema/badge.svg?branch=master)](https://coveralls.io/github/fuhrysteve/marshmallow-jsonschema?branch=master)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/python/black)\n\n marshmallow-jsonschema translates marshmallow schemas into\n JSON Schema Draft v7 compliant jsonschema. See http://json-schema.org/\n\n#### Why would I want my schema translated to JSON?\n\nWhat are the use cases for this? Let's say you have a\nmarshmallow schema in python, but you want to render your\nschema as a form in another system (for example: a web browser\nor mobile device).\n\n#### Installation\n\nRequires python>=3.6 and marshmallow>=3.11. (For python 2 & marshmallow 2 support, please use marshmallow-jsonschema<0.11)\n\n```\npip install marshmallow-jsonschema\n```\n\n#### Some Client tools can render forms using JSON Schema\n\n* [react-jsonschema-form](https://github.com/mozilla-services/react-jsonschema-form) (recommended)\n  * See below extension for this excellent library!\n* https://github.com/brutusin/json-forms\n* https://github.com/jdorn/json-editor\n* https://github.com/ulion/jsonform\n\n### Examples\n\n#### Simple Example\n\n```python\nfrom marshmallow import Schema, fields\nfrom marshmallow_jsonschema import JSONSchema\n\nclass UserSchema(Schema):\n    username = fields.String()\n    age = fields.Integer()\n    birthday = fields.Date()\n\nuser_schema = UserSchema()\n\njson_schema = JSONSchema()\njson_schema.dump(user_schema)\n```\n\nYields:\n\n```python\n{'properties': {'age': {'format': 'integer',\n                        'title': 'age',\n                        'type': 'number'},\n                'birthday': {'format': 'date',\n                             'title': 'birthday',\n                             'type': 'string'},\n                'username': {'title': 'username', 'type': 'string'}},\n 'required': [],\n 'type': 'object'}\n```\n\n#### Nested Example\n\n```python\nfrom marshmallow import Schema, fields\nfrom marshmallow_jsonschema import JSONSchema\nfrom tests import UserSchema\n\n\nclass Athlete(object):\n    user_schema = UserSchema()\n\n    def __init__(self):\n        self.name = 'sam'\n\n\nclass AthleteSchema(Schema):\n    user_schema = fields.Nested(JSONSchema)\n    name = fields.String()\n\n    \nathlete = Athlete()\nathlete_schema = AthleteSchema()\n\nathlete_schema.dump(athlete)\n```\n\n#### Complete example Flask application using brutisin/json-forms\n\n![Screenshot](http://i.imgur.com/jJv1wFk.png)\n\nThis example renders a form not dissimilar to how [wtforms](https://github.com/wtforms/wtforms) might render a form.\n\nHowever rather than rendering the form in python, the JSON Schema is rendered using the\njavascript library [brutusin/json-forms](https://github.com/brutusin/json-forms).\n\n\n```python\nfrom flask import Flask, jsonify\nfrom marshmallow import Schema, fields\nfrom marshmallow_jsonschema import JSONSchema\n\napp = Flask(__name__)\n\n\nclass UserSchema(Schema):\n    name = fields.String()\n    address = fields.String()\n\n\n@app.route('/schema')\ndef schema():\n    schema = UserSchema()\n    return jsonify(JSONSchema().dump(schema))\n\n\n@app.route('/')\ndef home():\n    return '''<!DOCTYPE html>\n<head>\n<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/brutusin.json-forms/1.3.0/css/brutusin-json-forms.css\"><Paste>\n<script src=\"https://code.jquery.com/jquery-1.12.1.min.js\" integrity=\"sha256-I1nTg78tSrZev3kjvfdM5A5Ak/blglGzlaZANLPDl3I=\" crossorigin=\"anonymous\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.min.js\"></script>\n<script src=\"https://cdn.jsdelivr.net/brutusin.json-forms/1.3.0/js/brutusin-json-forms.min.js\"></script>\n<script>\n$(document).ready(function() {\n    $.ajax({\n        url: '/schema'\n        , success: function(data) {\n            var container = document.getElementById('myform');\n            var BrutusinForms = brutusin[\"json-forms\"];\n            var bf = BrutusinForms.create(data);\n            bf.render(container);\n        }\n    });\n});\n</script>\n</head>\n<body>\n<div id=\"myform\"></div>\n</body>\n</html>\n'''\n\n\nif __name__ == '__main__':\n    app.run(host='0.0.0.0', debug=True)\n\n```\n\n\n### Advanced usage\n#### Custom Type support\n\nSimply add a `_jsonschema_type_mapping` method to your field\nso we know how it ought to get serialized to JSON Schema.\n\nA common use case for this is creating a dropdown menu using\nenum (see Gender below).\n\n\n```python\nclass Colour(fields.Field):\n\n    def _jsonschema_type_mapping(self):\n        return {\n            'type': 'string',\n        }\n\n    def _serialize(self, value, attr, obj):\n        r, g, b = value\n        r = \"%02X\" % (r,)\n        g = \"%02X\" % (g,)\n        b = \"%02X\" % (b,)\n        return '#' + r + g + b \n\nclass Gender(fields.String):\n    def _jsonschema_type_mapping(self):\n        return {\n            'type': 'string',\n            'enum': ['Male', 'Female']\n        }\n\n\nclass UserSchema(Schema):\n    name = fields.String(required=True)\n    favourite_colour = Colour()\n    gender = Gender()\n\nschema = UserSchema()\njson_schema = JSONSchema()\njson_schema.dump(schema)\n```\n\n\n### React-JSONSchema-Form Extension\n\n[react-jsonschema-form](https://react-jsonschema-form.readthedocs.io/en/latest/)\nis a library for rendering jsonschemas as a form using React. It is very powerful\nand full featured.. the catch is that it requires a proprietary\n[`uiSchema`](https://react-jsonschema-form.readthedocs.io/en/latest/form-customization/#the-uischema-object)\nto provide advanced control how the form is rendered.\n[Here's a live playground](https://rjsf-team.github.io/react-jsonschema-form/)\n\n*(new in version 0.10.0)*\n\n```python\nfrom marshmallow_jsonschema.extensions import ReactJsonSchemaFormJSONSchema\n\nclass MySchema(Schema):\n    first_name = fields.String(\n        metadata={\n            'ui:autofocus': True,\n        }\n    )\n    last_name = fields.String()\n\n    class Meta:\n        react_uischema_extra = {\n            'ui:order': [\n                'first_name',\n                'last_name',\n            ]\n        }\n\n\njson_schema_obj = ReactJsonSchemaFormJSONSchema()\nschema = MySchema()\n\n# here's your jsonschema\ndata = json_schema_obj.dump(schema)\n\n# ..and here's your uiSchema!\nui_schema_json = json_schema_obj.dump_uischema(schema)\n\n\n",
    "bugtrack_url": null,
    "license": "MIT License",
    "summary": "JSON Schema Draft v7 (http://json-schema.org/) formatting with marshmallow",
    "version": "0.13.0",
    "split_keywords": [
        "marshmallow-jsonschema",
        "marshmallow",
        "schema",
        "serialization",
        "jsonschema",
        "validation"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "335a17223353019169bdfcfd3683b79e",
                "sha256": "2814f2afb94a6e01b3c0a5795b3dfb142b628763655f20378400af5c0a2307fb"
            },
            "downloads": -1,
            "filename": "marshmallow_jsonschema-0.13.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "335a17223353019169bdfcfd3683b79e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 11812,
            "upload_time": "2021-10-21T18:02:39",
            "upload_time_iso_8601": "2021-10-21T18:02:39.392884Z",
            "url": "https://files.pythonhosted.org/packages/f6/cf/a620a7b0a5ba2aaa52e70f95795e0cf3a7f6332a7cb432a1223b61ac654e/marshmallow_jsonschema-0.13.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "md5": "cf38c60f67e176f71550d67b0ec068f3",
                "sha256": "f8ce19cfc0edd909e81f141d7420c33544b849bc5ebbfae8f6a3deea5a3b1f47"
            },
            "downloads": -1,
            "filename": "marshmallow-jsonschema-0.13.0.tar.gz",
            "has_sig": false,
            "md5_digest": "cf38c60f67e176f71550d67b0ec068f3",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 12703,
            "upload_time": "2021-10-21T18:02:40",
            "upload_time_iso_8601": "2021-10-21T18:02:40.923632Z",
            "url": "https://files.pythonhosted.org/packages/2f/53/109d80013b70b6140d05e521ad31e3014680007b51c3dfac72ad20a2d6ee/marshmallow-jsonschema-0.13.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2021-10-21 18:02:40",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "fuhrysteve",
    "github_project": "marshmallow-jsonschema",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "requirements": [
        {
            "name": "marshmallow",
            "specs": [
                [
                    ">=",
                    "3.11"
                ]
            ]
        }
    ],
    "tox": true,
    "lcname": "marshmallow-jsonschema"
}
        
Elapsed time: 0.01331s