Flame_Phoenix
Flame_Phoenix

Reputation: 17574

jsonschema does not validate json correctly

Background

I am trying to validate a JSON file using jsonchema in my Python code, however, I am having an error I cannot understand.

Code

from jsonschema import validate
import json

point_schema = {
    "$id": "https://example.com/schemas/point",
    "type": "object",
    "properties": {"x": {"type": "number"}, "y": {"type": "number"}},
    "required": ["x", "y"],
}

polygon_schema = {
    "$id": "https://example.com/schemas/polygon",
    "type": "array",
    "items": {"$ref": "https://example.com/schemas/point"},
}

a_polygon = [{'x': 1, 'y': 2}, {'x': 3, 'y': 4}, {'x': 1, 'y': 2}]
a_polygon_json = json.JSONEncoder.encode(a_polygon)

validate(instance=a_polygon_json, schema=polygon_schema)

Here I define a point and a polygon schemas. Basically, a polygon should be an array of points. As you can see, my a_polygon is an array.

Error

However, jsonschema, for reasons I cannot understand, does not see it the same way:

>>> validate(instance=a_polygon_json, schema=polygon_schema)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/user/anaconda3/envs/darwin-py/lib/python3.7/site-packages/jsonschema/validators.py", line 934, in validate
    raise error
jsonschema.exceptions.ValidationError: '[{"x": 1, "y": 2}, {"x": 3, "y": 4}, {"x": 1, "y": 2}]' is not of type 'array'

Failed validating 'type' in schema:
    {'$id': 'https://example.com/schemas/polygon',
     'items': {'$ref': 'https://example.com/schemas/point'},
     'type': 'array'}

On instance:
    '[{"x": 1, "y": 2}, {"x": 3, "y": 4}, {"x": 1, "y": 2}]'

Question

What am I doing wrong?

Upvotes: 0

Views: 1628

Answers (1)

Relequestual
Relequestual

Reputation: 12315

I think you don't want to do json.JSONEncoder.encode. Doing so turns the data structure into a string representation of your instance. The JSON Schema implementation expects unencoded JSON instances, based on the example in the docs.

validate(instance={"name" : "Eggs", "price" : 34.99}, schema=schema)

https://github.com/Julian/jsonschema

The error you're seeing is "A string is not an array" which is true. Easy mistake to make.

Upvotes: 1

Related Questions