Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate JSON data using python

I need to create a function that validates incoming json data and returns a python dict. It should check if all necessary fields are present in a json file and also validate the data types of those fields. I need to use try-catch. Could you provide some kind of snippets or examples that give me answers?

like image 524
LennyDan Avatar asked Feb 02 '19 07:02

LennyDan


People also ask

How do I validate a JSON file?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.

How do I check if a string is valid in JSON?

The common approach for checking if a String is a valid JSON is exception handling. Consequently, we delegate JSON parsing and handle the specific type of error in case of incorrect value or assume that value is correct if no exception occurred.

What is JSON input validation?

Validation of the input JSON message or the message tree is performed against the JSON schema files or OpenAPI definition files that are deployed. JSON schema must be contained in a file with a . json file extension, and it must either contain schema in the name (for example, . schema.

What is JSON Schema Python?

jsonschema is an implementation of the JSON Schema specification for Python. validate(instance={"name" : "Eggs", "price" : 34.99}, schema=schema) >>> validate( ... instance={"name" : "Eggs", "price" : "Invalid"}, schema=schema, ... ) It can also be used from console: $ jsonschema --instance sample.json sample.schema.


1 Answers

If you haven't check jsonschema library, it can be useful to validate data. JSON Schema is a way to describe the content of JSON. The library just uses the format to make validations based on the given schema.

I made a simple example from basic usage.

import json
from jsonschema import validate

# Describe what kind of json you expect.
schema = {
    "type" : "object",
    "properties" : {
        "description" : {"type" : "string"},
        "status" : {"type" : "boolean"},
        "value_a" : {"type" : "number"},
        "value_b" : {"type" : "number"},
    },
}

# Convert json to python object.
my_json = json.loads('{"description": "Hello world!", "status": true, "value_a": 1, "value_b": 3.14}')

# Validate will raise exception if given json is not
# what is described in schema.
validate(instance=my_json, schema=schema)

# print for debug
print(my_json)
like image 159
T.Nylund Avatar answered Oct 09 '22 06:10

T.Nylund