Validate JSON objects using Python DictShield

** I didn't notice it at all when I wrote it, but now it seems that it has moved to schematics. I will write the schematics version soon ... maybe. ** **


dictshield is a library for validating JSON objects.

Since it can be defined by class, it seems to be easy to use because it is similar to the model and form class of django that I usually use, the document class of mongoengine, etc., and the code base is compact and the visibility is good. trial. As you follow through the code, it seems that MongoDB and JSON Schema are also taken into consideration.

How to use

Basic edition

documents.py


from dictshield.document import Document
from dictshield.fields import StringField, IntField, FloatField, BooleanField, DateTimeField

class SampleDocument(Document):
    id = IntField(min_value=0)
    name = StringField()
    gps_attached = BooleanField()
    temperature = FloatField()
    created_at = DateTimeField()

Inspecting a JSON object converts the JSON object to dict and then throws it into the document class.

import json

json_data = '{"id": 1, "name": "foo", "gps_attached": true, "temperature": 23.5, "created_at": "2013-01-01T12:34:56" }'

data = json.loads(json_data)

document = SampleDocument(**data)
document.validate()  #True is returned

Handling of nested (?) JSON objects

To use a nested (?) JSON object, use the ʻEmbeddedDocument` class. An example of separating peripheral sensor information.

documents.py


from dictshield.document import Document, EmbeddedDocument
from dictshield.fields import StringField, IntField, FloatField, BooleanField, DateTimeField
from dictshield.fields.compound import EmbeddedDocumentField


class PeripheralEmbeddedDocument(EmbeddedDocument):
    gps_attached = BooleanField()
    temperature = FloatField()

class SampleDocument(Document):
    id = IntField()
    name = StringField(max_length=5)
    created_at = DateTimeField()
    peripheral = EmbeddedDocumentField(PeripheralEmbeddedDocument)
data = {
    u'created_at': u'2013-01-01T12:34:56',
    u'id': 1,
    u'name': u'foo',
    u'peripheral': {
        u'gps_attached': True,
        u'temperature': 23.5
    }
}

document = SampleDocument(**data)
document.validate()  #True is returned

exception

If validation fails, a ShieldException will be thrown.

data = {
    u'created_at': u'2013-01-01T12:34:56',
    u'id': 1,
    u'name': u'hogheoge',  #long
    u'peripheral': {
        u'gps_attached': True,
        u'temperature': 23.5
    }
}

document = SampleDocument(**data)
document.validate()
---------------------------------------------------------------------------
ShieldException                           Traceback (most recent call last)
<ipython-input-76-8d15894a526a> in <module>()
----> 1 document.validate()

/somewhere/lib/python2.7/site-packages/dictshield/document.pyc in validate(self, validate_all)
    333                 # NB: raising a ShieldDocException in this case would be more
    334                 # consistent, but existing code might expect ShieldException
--> 335                 raise err
    336
    337         if errs:

ShieldException: String value is too long - name:hogheoge

What I noticed


reference

Recommended Posts

Validate JSON objects using Python DictShield
[Python] JSON validation using Voluptuous
Python #JSON
Start using Python
Scraping using Python
Manipulate objects using Blender 2.8's low-level Python API
Operate Redmine using Python Redmine
[Python] Use JSON with Python
Fibonacci sequence using Python
Handling json in python
Data analysis using Python 0
Data cleaning using Python
Using Python #external packages
WiringPi-SPI communication using Python
Age calculation using python
Validate E-Mail with Python
Search Twitter using Python
Name identification using python
Notes using Python subprocesses
Try using Tweepy [Python2.7]
Python notes using perl-ternary operator
Flatten using Python yield from
Scraping using Python 3.5 async / await
Easily format JSON in Python
[S3] CRUD with S3 using Python [Python]
[Python] Try using Tkinter's canvas
About python objects and classes
About Python variables and objects
Using Quaternion with Python ~ numpy-quaternion ~
Try using Kubernetes Client -Python-
Python notes using perl-special variables
[Python] Using OpenCV with Python (Basic)
Scraping using Python 3.5 Async syntax
Website change monitoring using python
Post to Twitter using Python
Equivalence of objects in Python
Start to Selenium using python
Search algorithm using word2vec [python]
Change python version using pyenv
# 1 [python3] Simple calculation using variables
Create JIRA tickets using Python
Instrument control using Python [pyvisa]
Manipulate spreadsheets locally using Python
Python memo using perl --join
Web scraping using Selenium (Python)
[Python] I tried using OpenPose
Recognize red objects with python
Broadcast on LINE using python
Format json with Vim (with python)
Data analysis using python pandas
Translate using googletrans in Python
Using Python mode in Processing
Using OpenCV with Python @Mac
[Python] Shooting game using pyxel
Send using Python with Gmail
Read json data with python