Parthapratim Neog
Parthapratim Neog

Reputation: 4478

How to validate a json structure in Python3

I am using Python3.5 and Django for a web api.When I refer to input, I refer to a HTTP request parameters. I have a parameter where I am expecting a JSON data which I need to validate before processing further.

I have a base json structure that the input has to be in. Example,

{
  "error": "bool",
  "data": [
      {
        "name": "string",
        "age": "number"
      },
      {
        "name": "string",
        "age": "number"
      },
      ...
    ]
}

The above JSON represents the structure that I want my input to be in. The keys are predefined, and the value represents the datatype of that key that I am expecting. I came across a Python library(jsonschema) that does this validation, but I can't find any documentation where it works with dynamic data. i.e. the objects inside the JSON array 'data' can be of any number, of course this is the most simple scenario I came up with for explaining the basic requirement. In cases like these, how can I validate my json?

The solution here didn't help because it's just checking if the json is proper or not based on the Django model. My json has no relation with Django model. Its a simple json structure. It still doesn't tell me how to validate dynamic object

Upvotes: 5

Views: 10259

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599580

JSON Schema is a specification for validating JSON; jsonschema is just a Python library that implements it. It certainly does allow you to specify that a key can contain any number of elements.

An example of a JSON Schema that validates your code might be:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "additionalProperties": false,
  "required": [
    "error",
    "data"
  ],
  "properties": {
    "error": {
      "type": "boolean"
    },
    "data": {
      "type": "array",
      "items": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "name": {
            "type": "string"
          },
          "age": {
            "type": "integer"
          }
        }
      }
    }
  }
}

See https://spacetelescope.github.io/understanding-json-schema/ for a good overview

Upvotes: 7

Nathangrad
Nathangrad

Reputation: 1464

Take a look into the documentation of Python's JSON API. I believe json.tool is what you're looking for, however there are a couple of other ways to validate JSON using that API.

Upvotes: -1

Related Questions