Validate python dictionaries (mongodb docs etc) using a JSON schema
Project description
dict-schema-validator
Validate python dictionaries (mongodb docs etc) using a JSON schema.
JSON Schema example
Here is a simple schema representing a Customer
:
{
"_id": "ObjectId",
"created": "date",
"is_active": "bool",
"fullname": "string",
"age": ["int", "null"],
"contact": {
"phone": "string",
"email": "string"
},
"cards": [{
"type": "string",
"expires": "date"
}]
}
Getting Started
from datetime import datetime
import json
from dict_schema_validator import validator
with open('models/customer.json', 'r') as j:
schema = json.loads(j.read())
customer = {
"_id": 123,
"created": datetime.now(),
"is_active": True,
"fullname": "Jorge York",
"age": 32,
"contact": {
"phone": "559-940-1435",
"email": "york@example.com",
"skype": "j.york123"
},
"cards": [
{"type": "visa", "expires": "12/2029"},
{"type": "visa"},
]
}
errors = validator.validate(schema, customer)
for err in errors:
print(err['msg'])
Output:
[*] "_id" has wrong type. Expected: "ObjectId", found: "int"
[+] Extra field: "contact.skype" having type: "str"
[*] "cards[0].expires" has wrong type. Expected: "date", found: "str"
[-] Missing field: "cards[1].expires"
Supported Field Types
- string
- bool
- int
- float
- number (value can have
int
orfloat
type) - date (for
datetime
) - null (for
None
values) - ObjectId (for
bson.objectid.ObjectId
)
JSON Schema Format
- Exact type: "field_1" : "type"
- One of the possible types: "field_1" : ["type1", "type2"]
- Define a dictionary: "field_1": {"field_1_1" : "type", ...}
- Define an array: "field_1": [ {"field_1_1" : "type", ...} ]
TODO
- enums for string type
- value validators
- required (true, false) attribute for fields
- array of base types support
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Close
Hashes for dict-schema-validator-0.1.2.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 851ea6ae1082efa125dc87d68a76457bca9d8092fd9dd029596495180a0a7b04 |
|
MD5 | b85211e7cff84d9576aa5fbde5ae86cf |
|
BLAKE2b-256 | 1eb7db9dd6aae4852e23a5a2f4d48fcc545e2afe89aaa7f46d490ed400d4ef5c |
Close
Hashes for dict_schema_validator-0.1.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 89bb44c703f2edfa812dd2d8d7cc9e23b2ea1b566cdfad5e1303c204dc596597 |
|
MD5 | e6d8dca8f870b761d2523a58e51d877c |
|
BLAKE2b-256 | fa3d0a7ba6594c5ee24bf1c03f3df787f72d5e7a7e123b4afd05293a8d4ee6ec |