Home > other >  Validation Json Schema
Validation Json Schema

Time:11-11

I am trying to validate the json for required fields using python. I am doing it manually like iterating through the json reading it. Howerver i am looking for more of library / generic solution to handle all scenarios.

For example I want to check in a list, if a particular attribute is available in all the list items.

Here is the sample json which I am trying to validate.

{
    "service": {
        "refNumber": "abc",
        "item": [{
            "itemnumber": "1",
            "itemloc": "uk"
        }, {
            "itemnumber": "2",
            "itemloc": "us"
        }]
    }
}

I want to validate if I have refNumber and itemnumber in all the list items.

CodePudding user response:

A JSON Schema is a way to define the structure of JSON.

There are some accompanying python packages which can use a JSON schema to validate JSON (jsonschema).

The JSON Schema for your example would look approximately like this:

{
    "type": "object",
    "properties": {
        "service": {
            "type": "object",
            "properties": {
                "refNumber": {
                    "type": "string"
                },
                "item": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "itemnumber": {
                                "type": "string"
                            },
                            "itemloc": {
                                "type": "string"
                            }
                        }
                    }
                }
            }
        }
    }
}

i.e., an object containing service, which itself contains a refNumber and a list of items.

CodePudding user response:

Since i dont have enough rep to add a comment i will post this answer.

First i have to say i dont program with python.

According to my google search, you have a jsonschema module available for Python.

from jsonschema import validate
schema = {
    "type": "object",
    "properties": {
        "service": {"object": {
                                 "refNumber": {"type" : "string"},
                                 "item: {"array": []}
                              },
                     "required": ["refNumber"]
                  },
             
    },

}


validate(instance=yourJSON, schema=yourValidationSchema)

This example is not tested, but you can get some idea,

Link to jsonschema docs

  • Related