How to validate JSON data in Python?
Published on Aug. 22, 2023, 12:17 p.m.
To validate JSON data in Python, you can use the jsonschema
library. This library allows you to define a JSON schema, which describes the structure and validation rules for your JSON data. You can then use the jsonschema.validate()
function to validate your JSON data against this schema. Here’s an example:
import json
from jsonschema import validate
# Define a JSON schema
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number"}
},
"required": ["name", "age"]
}
# Example JSON data to validate against the schema
json_data = '{"name": "John", "age": 30}'
# Parse the JSON data into a Python object
data = json.loads(json_data)
# Validate the data against the schema
validate(data, schema)
In this example, we define a JSON schema that specifies that the JSON data should be an object with two properties: “name” (a string) and “age” (a number). We then parse some JSON data into a Python object and use the jsonschema.validate()
function to validate it against the schema. If the data is valid, the function will return normally. If the data is not valid, it will raise a ValidationError
with a detailed error message.
It’s important to note that the jsonschema
library is relatively powerful and can handle more complex validation rules beyond simple type checking. For example, you can define arrays, nested objects, regular expressions, custom validation functions, and more.