Validate JSON data using python

前端 未结 3 1847
日久生厌
日久生厌 2021-01-03 06:42

I’m pretty new in python so would you be so kind to help me? It seems to be really trivial question. I need to create a function that validates incoming json data and return

3条回答
  •  独厮守ぢ
    2021-01-03 07:32

    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)
    

提交回复
热议问题