JSONLINT: parse the python json data validation library instance, jsonlintjson
JSON (JavaScript Object Notation) is a lightweight data exchange format that is easy to read and write.
JSON Functions
To use the JSON function, you must import the json Library: import json.
Function |
Description |
Json. dumps |
Encodes a Python object into a JSON string. |
Json. loads |
Decodes the encoded JSON string into a Python object. |
With the popularity of frontend and backend separation and REST APIs, developers are constantly looking for a flexible and elegant way to verify json data. If you directly obtain data for verification or use json scheme for verification. The former easily makes the function lengthy, and there may be a lot of repeated verification; the latter verification is not flexible.
The jsonlint introduced in this article is inspired by the python Form verification tool wtforms. wtforms can also perform json data verification by inheriting the Form class, but wtforms can perform json Array (Array) type processing has a very strange behavior, the need to pass the array data through the A-1, A-2, often cannot effectively process the array data. Most of jsonlint code is wtforms, which can be considered as a branch of wtforms. However, jsonlint deletes the form rendering part of wtforms and changes the input data format. The most important thing is to use the correct logic to verify the Array and Object types. The following are some examples:
Json verification of the basic string type
For the basic string type, you only need to create a Json subclass and enter the corresponding Field. Usage and wtforms:
from jsonlint import Jsonfrom jsonlint.fields import StringFieldfrom jsonlint.validators import DataRequiredclass MyLint(Json): name = StringField(validators=[DataRequired()])mylint = MyLint({'name': 'demo'})print mylint.validate() # Trueprint mylint.name.data # demo
More flexible json data verification
Jsonlint inherits the advantages of wtforms and can perform some more flexible custom json data verification. As long as the Instance name of the field class is written into the validate_fieldname function, you can customize verification and modify the field:
from jsonlint import Jsonfrom jsonlint.fields import IntegerFieldfrom jsonlint.validators import ValidationErrorclass AgeLint(Json): age = IntegerField() def validate_age(form, field): if field.data < 13: raise ValidationError("We're sorry, you must be 13 or older to register")agelint = AgeLint({'age': 12})print agelint.validate() # Falseprint agelint.age.errors # ["We're sorry, you must be 13 or older to register"]
Verify the array type
Jsonlint was born to solve the problem of how to verify the array type, which is easy to implement in jsonlint:
from jsonlint import Jsonfrom jsonlint.fields import StringField, ListFieldfrom jsonlint.validators import DataRequired, ValidationErrorclass ListLint(Json): cars = ListField(StringField(validators=[DataRequired()])) def validate_cars(form, field): if 'BMW' in field.data: raise ValidationError("We're sorry, you cannot drive BMW")listlint = ListLint({'cars': ['Benz', 'BMW', 'Audi']})print listlint.validate() # Falseprint listlint.cars.errors # ["We're sorry, you cannot drive BMW"]
As a Field container, the ListField class can accommodate arrays of other types of fields and pass in arrays of the corresponding type directly for effective verification. ListField can also be used for custom verification.
Verify the object type
Object types often exist in some REST APIs web applications, and jsonlint is also supported. You only need to pass the Json subclass to the ObjectField for verification:
from jsonlint import Jsonfrom jsonlint.fields import ObjectField, IntegerField, BooleanFieldclass T(Json): status = BooleanField() code = IntegerField()class DataLint(Json): data = ObjectField(T)datalint = DataLint({'data': {'status': True, 'code': 200}})print datalint.validate() # Falseprint datalint.data.code.data # 200
Conclusion
The original intention of jsonlint was that I wanted to use a method similar to wtforms to verify json. This not only provides a good verification method, but also separates the business and avoids the lengthy process of Interface main functions. For example, you can define a class:
class RegisterLint(UserLint): def validata_nickname(self, field): ... def validate_account(self, field): ... def create_user(self): ...user = RegisterLint()
In this way, you can use the instance user of RegisterLint to authenticate data, and directly execute user. create_user () for database operations to better encapsulate the database logic. This can be said to be an independent layer based on the MVC design pattern.
To try jsonlint, you can install it directly using pip:
pip install jsonlint
Finally, jsonlint open source at Github: https://github.com/tangwz/jsonlint
Jsonlint is only maintained by me at this stage. Although the unit test coverage rate is as full as possible, it does not mean that there are no bugs. I hope you will give your valuable comments or maintain and iterate jsonlint together:
Https://github.com/tangwz/jsonlint/issues
If you use Flask for web development, you can also use the encapsulated Flask and jsonlint Library: Flask-Lint