Giter VIP home page Giter VIP logo

jsonschema's Introduction

jsonschema

PyPI version Supported Python versions Build status ReadTheDocs status pre-commit.ci status Zenodo DOI

jsonschema is an implementation of the JSON Schema specification for Python.

It can also be used from the command line by installing check-jsonschema.

Features

Installation

jsonschema is available on PyPI. You can install using pip:

Extras

Two extras are available when installing the package, both currently related to format validation:

  • format
  • format-nongpl

They can be used when installing in order to include additional dependencies, e.g.:

Be aware that the mere presence of these dependencies โ€“ or even the specification of format checks in a schema โ€“ do not activate format checks (as per the specification). Please read the format validation documentation for further details.

Running the Test Suite

If you have nox installed (perhaps via pipx install nox or your package manager), running nox in the directory of your source checkout will run jsonschema's test suite on all of the versions of Python jsonschema supports. If you don't have all of the versions that jsonschema is tested under, you'll likely want to run using nox's --no-error-on-missing-interpreters option.

Of course you're also free to just run the tests on a single version with your favorite test runner. The tests live in the jsonschema.tests package.

Benchmarks

jsonschema's benchmarks make use of pyperf. Running them can be done via:

$ nox -s perf

Community

The JSON Schema specification has a Slack, with an invite link on its home page. Many folks knowledgeable on authoring schemas can be found there.

Otherwise, opening a GitHub discussion or asking questions on Stack Overflow are other means of getting help if you're stuck.

About

I'm Julian Berman.

jsonschema is on GitHub.

Get in touch, via GitHub or otherwise, if you've got something to contribute, it'd be most welcome!

You can also generally find me on Libera (nick: Julian) in various channels, including #python.

If you feel overwhelmingly grateful, you can also sponsor me.

And for companies who appreciate jsonschema and its continued support and growth, jsonschema is also now supportable via TideLift.

jsonschema's People

Contributors

ankostis avatar apamnapat avatar apiraino avatar bayandin avatar bouke avatar bsmithers avatar cdunklau avatar davidkorczynski avatar dependabot[bot] avatar dnephin avatar gableroux avatar gazpachoking avatar helrond avatar hynek avatar joepvandijken avatar johnthagen avatar julian avatar lennart-k avatar martinzugnoni avatar naimetti avatar nezhar avatar opethe1st avatar pre-commit-ci[bot] avatar romaintt avatar sirosen avatar sontek avatar stranger6667 avatar willson-chen avatar zac-hd avatar zewt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsonschema's Issues

Error reporting in case of multi option type

Hi Julian,

this time I would like to ask something. Consider the following setup

my_schema = {
    "type": [
        "string",
        {
            "type": "array",
            "items": { "type": "number" },
            "additionalItems": False
        }
    ]
}

my_json = [1, "test"]


Draft3Validator.check_schema(my_schema)
print 'schema is valid'

v = Draft3Validator(my_schema)

valid = True
for error in sorted(v.iter_errors(my_json), key=str):
    valid = False
    print error

if valid: 
    print 'json is valid'

The output I get for this is

schema is valid
[1, 'test'] is not of type 'string', {'items': {'type': 'number'}, 'additionalItems': False, 'type': 'array'}

However it seems to me that the error should read

'test' is not of type 'number'

Do you think it is possible that in such case of multiple options an error of the deepest match should be presented?
Or, as an alternative, there may be a set of errors like

[1, 'test'] is not of type 'string'
'test' is not of type 'number'

xpath like string in error message.

The error message in the current ValidationError is not helpful in identifying the invalid tag.

The validator raises error message such as these:

Error1: ["u'name' is a required property"]

We need a better way to identify such errors.
I propose we use a jsonpath-like[1] string that indicates the "path" to the invalid tag.

Ex.

x["persons"][0]["location"]["city"]

In a document like this:

{
  "persons": [
    {
      "location": {
        "city": "New York"
     }
   }
  ]
}

Having this "jsonpath" will aslo make it posible to indicate the row and the line the error has occurred on if you have some sort of tag database.

I am more then willing to implement this feature myself, but I require some pointers to get started.
I am looking for the functions that get called when someone starts validating a new element from an array or a tag from an object.

These functions need to be recursive so I can easily track the parents of the current tag.
Basically to use the function stack as a way to infer the parents of a tag.

[1] http://goessner.net/articles/JsonPath/

JSON error output

Would love to see the error message returned as a list of JSON-valid dicts (error code, message, affected key, offending value, reason it failed).

I'm trying to do this on my own (poorly) but returning the key of the value is important to my error messaging so that the user knows which key/property needs to be fixed. Right now the error message is non-specific.

$ref attribute

Hello Julian,

Are you planning to implement support of $ref attribute in your library?
$ref attribute gives a lot of flexibility in building schemas for validating dynamic JSONs.

Thanks.

divisibleBy with floating point numbers

import jsonschema

s = {
                "type": "object",
                "properties": {
                    "price": {
                        "type": "number",
                        "divisibleBy": 0.01
                    }
                }
}

jsonschema.validate({"price":1.09}, s) # fail
jsonschema.validate({"price":1.89}, s) # OK

ipv6 format checking on Windows

Windows does not have the socket.inet_pton function, I think we need to handle that like colors, and only add the validator if it is available.

Valid schema with 0.6 fails with 1.1

I have the following schema:

{
    "name":"Pathway",
    "properties":{
        "name":{
            "description":"The name of the pathway",
            "type":"string",
            "required":true
        },
        "marker":{
            "description":"The gene type used by the pathway",
            "type":"string",
            "required":true,
            "enum": [
                "ENTREZID",
                "ENSEMBL",
                "UNIPROT",
                "REFSEQ",
                "SYMBOL",
                "ENSEMBLTRANS",
                "UNIGENE"
            ]
        },
        "species":{
            "description": "The species the pathway belongs to",
            "type": "string",
            "required": true,
            "enum": [
                "homo_sapiens",
                "mus_musculus",
                "rattus_norvegicus",
                "saccaromyces_cerevisiae"
            ],
            "default": "homo_sapiens"
        },
        "genes":{
            "description": "The genes which form part of the pathway",
            "type": "array",
            "minItems": 2,
            "required": true,
            "uniqueItems": true
        },
        "source":{
            "description": "The source the pathway was taken from",
            "type": "string",
            "required": false
        },
        "pwf_version":{
            "description": "The version of the pathway format",
            "type":"number",
            "required": "true",
            "default": 1.0
            }
    }
}

After upgrading from 0.6 to 1.1, this no longer validates correctly: I get a SchemaError stating

SchemaError: True is not of type u'array'

The error occurs with "required". I'm not sure if 0.6 was wrong in letting this schema validate, or if it is a regression.

Not adding to the path on require:true validation error

Hi,

You are missing adding to the path when a validation error happens because require:true is not fulfilled
In line 393 you should add:

error.path.append(property)

to make sure that we know which require:true failed

Thanks

Merging $ref support had a 10x performance hit

Merging #37 / #41 put performance on the perftest down the tubes.

โŠ™  git checkout -q a8656b8d75944a0029376a0ed78f91c0cb7c886f && ./perftest
Validated 1000 times. Finished in 11.2677850723 seconds.

โŠ™  git checkout -q 0e87ffafc8c2bd && ./perftest
Validated 1000 times. Finished in 1.6240568161 seconds.

I have a slight feeling that this may be due to a poorly written performance test (or at least one that doesn't properly reflect real world use) but this definitely needs to be investigated.

Built-in format checker changes

It would be nice if all of the built in format checkers were available in the FormatChecker class, to ease the creation of an instance with a custom subset of any of the format checkers available.

We currently provide draft3_ and draft4_format_checker instances, which have the subset of checkers defined in each draft. These are a bit problematic, as it might be unexpected when format checkers defined in the spec are not available in them due to required libraries being present. Not sure what the best solution is yet.

$ref resolution scope

Currently the RefResolver does not alter the resolution scope when the "id" keyword is encountered. This can lead to problems when dereferencing. Consider the following schema:

{
    "id": "http://somewhere/schema.json",
    "definitions": {
        "subschema": {
            "id": "subschema.json",
            "definitions": {
                "subsubschema1": {},
                "subsubschema2": {"$ref": "#/definitions/subsubschema1"}
            }
        }
    }
}

Currently we would resolve the ref as http://somewhere/schema.json#/definitions/subsubschema1, which would cause a RefResolutionError as it does not exist. The proper resolution would be http://somewhere/subschema.json#/definitions/subsubschema1.

This is the same issue #60 is trying to address, but that PR doesn't actually solve the problem fully. What I was calling 'context' in that ticket, is actually called 'resolution scope' in the specification, and it needs to change both when we are inside a remote reference (which is what that PR currently covers,) as well as when we encounter an id keyword in the same schema (which is not covered in that PR.)

Return json tree with no invalid objects

I need to return json tree after validate, but without elements which didn't pass Schema Validator
example:

schema = {
    "type":"object",
    "properties":{
        "A":{"type" : "number"},
        "B":{"type" : "number"},
        "C":{"type" : "number"}
        }
    }
}

instance = {
    "A":1,
    "B":"spam",
    "C":3
}

method must be return:

 {
    "A":1,
    "C":3
}

I try to write it function by myself, but found it impossible, 'cause I can't get a full path to exception (see issue #52 )

Decide what to do with additionalProperties with patternProperties present

Good day,

looks like I found incorrect behavior.

simple code example:

    instance = {"foo": 123}
    schema = {
        "type": "object",
        "property": {
            "foo": {
                "type": "integer"
            },
        },
        "additionalProperties": {
            "type": "string"
        }
    }
    validate(instance, schema)

raises

Traceback (most recent call last):
  File "/Users/psih/Work/nimble-all/server/spikes/json_parser.py", line 192, in <module>
    validate(instance, schema)
  File "/Users/psih/Work/nimble-all/server/eggs/jsonschema-0.5-py2.7.egg/jsonschema.py", line 653, in validate
    validator.validate(instance, schema, meta_validate=meta_validate)
  File "/Users/psih/Work/nimble-all/server/eggs/jsonschema-0.5-py2.7.egg/jsonschema.py", line 332, in validate
    raise error
jsonschema.ValidationError: 123 is not of type 'string'

from my standpoint:
validate_additionalProperties should be called at least
validate_additionalProperties should be aware of all the previous validated properties

Add an AUTHORS file.

The # of committers has exceeded 10. That's usually a good number to start recording this :).

Customizable error messages

I was considering a modification to allow replacing one or more of the validation error messages with alternatives -- perhaps phrased differently (to meet an application's style guidelines) or in different languages. The basic idea would be to have all of the places that generate error messages use a function that pulls the template from a dictionary in the Validator instance, and fall back to the "stock" messages if none is found. Would this be a welcome addition?

Non-required string field fails validation when set to None

This ticket is to start a discussion. If a non-required field is set to None in the object being validated, should it throw a validation error?

Two cases:

{
    "required_field": "not None",
    "non_required_field": None
}

vs.

{
    "required_field": "not None"
}

Should these two objects validate in the same way?

ErrorTree.errors is always empty

ErrorTree instances have always an empty dictionary in the "errors" attribute, because nothing is assigned to it during class initialization.

Custom errors from format checkers?

I'm not sure if it would be a common enough use, but in my case I want custom error messages from format checkers. Wanted to see if this would be useful to support directly in jsonschema, or if I should just implement in my project.

Was thinking the checker functions could optionally raise a ValidationError that validate_format would then catch and yield.

ValidationError -- better detail

Julian,

I modified your code to have ValidationError provide more detail

In [15]: try:
   ....:        jsonschema.validate(message, EVENT_TYPE_CREATE, stop_on_error=False)
   ....: except jsonschema.ValidationError as err:
   ....:        print err.detail
   ....: 
{'organized_flag': [u"'yes' is not of type 'boolean'"], 'parent_id': [u'-30 is less than the minimum of 0'], 'name': [u"'name' is a required property"]}

ie.,
https://gist.github.com/2158863

would there be a reason not to do this?

Cheers,
-K

Intermittent failure in TestValidationDetails.test_single_nesting

This is a really stupid test anyways, and the whole thing should be fixed, but the cause of the failure is that something is wrong with sorted_errors when there are two matching error validators, which sometimes puts maximum before enum.

I've only seen the failure on Python 3.3.

Port the Test Suite to JSON

We discussed it a bit over here, just wanted to get your input on what sort of format you think the tests should be in? Should they be defined in json, maybe something like this?

{
    "name": "integer",
    "version": ["draft 3", "draft 4"],
    "schema": {"type": "integer"},
    "tests": [
        ["integer", 1, "valid"],
        ["number", 1.1, "invalid"]
    ]
}

Performance tests

There needs to be some basic (and non-basic) performance tests written to keep watch over performance and give some ballpark numbers for where things lie.

Dependencies Validation

I'm not sure if this is an issue with my understanding of the code, or of my understanding of the spec, or an actual issue. It seems to me that the validation for 'dependencies' is wrong.

Currently dependencies is validated in the validate_properties method, and is grabbed from the subschema, which does not seem right to me. Since I've rewritten my explanation like 5 times now without making it clear, I'll just include a code block of how I understand it should work:

def validate_dependencies(self, dependencies, instance, schema):
    for property, dependency in dependencies.iteritems():
        if property in instance:
            if self.is_type(dependency, "object"):
                for error in self.iter_errors(
                    instance, dependency, meta_validate=False
                ):
                    yield error
            else:
                dependency = _list(dependency)
                for dep in dependency:
                    if dep not in instance:
                        yield ValidationError(
                            "%r is a dependency of %r" % (dependency, property)
                        )

I would have just issued a pull request, but I can't be certain it isn't just my understanding of that property that is the problem. The spec is very confusing.

Friendly error messages for union types

When a given instance doesn't match any of multiple unioned schemas, it might be nice if the error message printed the name of the schemas (if present) rather than the full schema.

So for the following schema: {"type": [{"name": "Foo", "type": "boolean"}, {"name": "Bar", "type": "string"}]} the error message could be: blah is not of type 'Foo', or 'Bar' rather than blah is not of type {"name": "Foo", "type": "boolean"} or {"name": "Bar", "type": "string"}

Set default value in instance

Could there be a a way of setting in the instance the default values of properties as defined in the schema.
I am porting some setting code from ConfigObj3 to json/schema and this is the last thing that is missing for me!

Thanks for the great work

Schema works in V0.5 & not working in V0.8 & 1.0-dev also

Hi Julian,

schema1 = {"properties": {"body": {"items": {"required": True, "type": "object", "id": "0", "properties": {"timestamp": {"required": True, "type": "string", "id": "timestamp"}, "params": {"required": "false", "type": "object", "id": "params", "properties": {"Temperature": {"required": "false", "type": "object", "id": "Temperature", "properties": {"value": {"required": "false", "type": "number", "id": "value"}, "unit": {"required": "false", "type": "string", "id": "unit"}}}}}, "location": {"required": True, "type": "object", "id": "location", "properties": {"lat": {"required": True, "type": "number", "id": "lat"}, "lng": {"required": True, "type": "number", "id": "lng"}}}, "nodeid": {"required": True, "type": "string", "id": "nodeid"}}}, "required": True, "type": "array", "id": "body"}, "header": {"type": "object", "properties": {"gatewayid": {"required": True, "type": "string"}, "org": {"required": True, "type": "string"}, "type": {"required": True, "type": "string"}, "seqno": {"required": True, "type": "number"}, "streamid": {"required": True, "type": "string"}}}, "schemakey": {"required": True, "type": "string", "id": "schemakey"}}, "required": True, "type": "object", "id": "datacore0.2", "schema": "http://json-schema.org/draft-03/schema"}

schema2 = {"properties": {"body": {"items": {"required": True, "type": "object", "id": "0", "properties": {"timestamp": {"required": True, "type": "string", "id": "timestamp"}, "params": {"required": True, "type": "object", "id": "params", "properties": {"Temperature": {"required": False, "type": "object", "id": "Temperature", "properties": {"value": {"required": False, "type": "number", "id": "value"}, "unit": {"required": False, "type": "string", "id": "unit"}}}}}, "location": {"required": True, "type": "object", "id": "location", "properties": {"lat": {"required": True, "type": "number", "id": "lat"}, "lng": {"required": True, "type": "number", "id": "lng"}}}, "nodeid": {"required": True, "type": "string", "id": "nodeid"}}}, "required": True, "type": "array", "id": "body"}, "header": {"required": False, "type": "object", "id": "header", "properties": {"gatewayid": {"required": False, "type": "string", "id": "gatewayid"}, "org": {"required": False, "type": "string", "id": "org"}, "streamid": {"required": False, "type": "string", "id": "streamid"}, "type": {"required": False, "type": "string", "id": "type"}, "seqno": {"required": False, "type": "number", "id": "seqno"}}}, "schemakey": {"required": False, "type": "string", "id": "schemakey"}}}

data = {"body": [{"timestamp": "1361273664038", "params": {"Temperature": {"unit": "C", "value": 35.700000000000003}}, "nodeid": "GMR/6L/TS1", "location": {"lat": 13.081, "lng": 80.274000000000001}}], "header": {"gatewayid": "GMT/6L/GW100", "org": "example.com", "streamid": "23", "type": "DATA", "seqno": 1}, "schemakey": "CATGY_221360650604771"}

  1. If I validate schema1 against the above data in jsonschema v0.8 & v1.0.0-dev I am getting SchemaError, but works in V0.5.
  2. But with schema2 all the versions(v0.5, v0.8 & v1.0.0-dev) are working. But I want the validation should work in latest v0.8.

Could you please resolve if something is really went wrong in schema or in new Schema validator ?

Thanks,
Sakthivel

Draft 4 support

I started writing up a bit of code for the current revision of draft 4. Branch is here
I haven't done any testing, or added unit tests, so it is liable to be broken, just thought I'd let people know I'm working on it.

Array items reference problem

Hi,

updated jsonschema to 1.1.0 today and now I'm facing the following problem. Given is a simple schema like this:

{
    "type": "object",
    "$schema": "http://json-schema.org/draft-03/schema",
    "id": "#",
    "required": false,
    "properties": {
        "record_object": {
            "type": "object",
            "id": "record",
            "properties": {
                "mimetype": {
                    "type": "string"
                 }
            }
        },
        "event_object": {
            "type": "object",
            "id": "event",
            "properties": {
                "actions": {
                    "type": "array",
                    "id": "actions",
                    "items": {
                        "type": "object",
                        "$ref": "#/properties/record_object"
                    }
                }
            }
        } 
    }
}

Trying to validate the following JSON (or any other) raises an exception:

event = { "event_object": {
    "actions": [
        { 
            "mimetype": "test"
        }
    ]
}}

validate(event, schema)
 Traceback (most recent call last):
  File "gsa_schema.py", line 120, in <module>
    validate(event, s) 
  File "/Users/jan/Documents/code/jira/lib/python2.7/site-packages/jsonschema.py", line 1301, in validate
    cls(schema, *args, **kwargs).validate(instance)
  File "/Users/jan/Documents/code/jira/lib/python2.7/site-packages/jsonschema.py", line 226, in validate
    for error in self.iter_errors(*args, **kwargs):
  File "/Users/jan/Documents/code/jira/lib/python2.7/site-packages/jsonschema.py", line 219, in iter_errors
    for error in errors:
  File "/Users/jan/Documents/code/jira/lib/python2.7/site-packages/jsonschema.py", line 436, in validate_properties
    for error in self.iter_errors(instance[property], subschema):
  File "/Users/jan/Documents/code/jira/lib/python2.7/site-packages/jsonschema.py", line 219, in iter_errors
    for error in errors:
  File "/Users/jan/Documents/code/jira/lib/python2.7/site-packages/jsonschema.py", line 436, in validate_properties
    for error in self.iter_errors(instance[property], subschema):
  File "/Users/jan/Documents/code/jira/lib/python2.7/site-packages/jsonschema.py", line 219, in iter_errors
    for error in errors:
  File "/Users/jan/Documents/code/jira/lib/python2.7/site-packages/jsonschema.py", line 268, in validate_items
    for error in self.iter_errors(item, items):
  File "/Users/jan/Documents/code/jira/lib/python2.7/site-packages/jsonschema.py", line 219, in iter_errors
    for error in errors:
  File "/Users/jan/Documents/code/jira/lib/python2.7/site-packages/jsonschema.py", line 403, in validate_ref
    with self.resolver.resolving(ref) as resolved:
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 17, in __enter__
  File "/Users/jan/Documents/code/jira/lib/python2.7/site-packages/jsonschema.py", line 1026, in resolving
    document = self.resolve_remote(uri)
  File "/Users/jan/Documents/code/jira/lib/python2.7/site-packages/jsonschema.py", line 1099, in resolve_remote
    result = json.loads(urlopen(uri).read().decode("utf-8"))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 386, in open
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 248, in get_type
ValueError: unknown url type: actions

In case I do something wrong here please point me to it. Thanks in advance.
Jan

Issues with unique item identification

The helper function _uniq has a couple problems.

  • True and 1 are not considered unique. (Same for 0 and False)
  • The sorted container is not actually used in the second implementation with islice

Error path incorrect

I think there is an issue calculating the path of errors. Just dumping this here for now until I can investigate further. First impression is that additionalProperties validator is not appending path to error.

{
  "series": {
    "settings": {
      "a": "aeou"
    }
  }
}

The error: u'aeou' is not of type u'object, the path: series/settings (should be series/settings/a)

patternProperties makes the validator crash if the validated instance is not an object

Hi Julian,

please consider this testcase

    {
        "description": "check for patternProperties when the instance is not an object",
        "schema":{
            "type": "object",
            "patternProperties": {
                "^a[0-9]+$": { "type": "number" }
            },
            "additionalProperties": false    
        },
        "tests": [
            {
                "description": "a valid instance",
                "data": { "a1": 1 },
                "valid": true
            },
            {
                "description": "an invalid instance",
                "data": 1,
                "valid": false
            },
            {
                "description": "another invalid instance",
                "data": "test",
                "valid": false
            }
        ]
    }

basically, this is true for higher complexity situations, when the objects are nested and so on. But the cases above should be sufficient to clear the bug.

Thanks!

remote ref parsing

There is currently a problem with the remote ref parsing (at least on python 3.) urlopen returns bytes, which json.load doesn't like; he wants a string.

ErrorTree must be return full path to error object

It's issue is common by issue #36

I need to know, what block of code in json invoke exception

Here is code for example:

schema = {
    "type":"object",
    "properties":{
        "A":{
            "type":"object",
            "properties":{
                "B":{
                    "type":"object",
                    "properties":{
                        "C":{
                            "type" : "array",
                            "items" : {"type" : "number"},
                            "minItems" : 3
                        }
                    }
                }
            }
        }
    }
}

instance = {"A":{"B":{"C":["spam"]}}}

Trying to get Tree of Errors:

v = Draft3Validator(schema)
tree = ErrorTree(v.iter_errors(instance))
print(tree)
print(tree.errors)

It return:

<ErrorTree (2 total errors)>
{}

Now, how can I handle where there was my error?
oh, ok. I already read issue #36 , and try this code:

for x in tree:
    print(x)

It return:

0
A

But in fin:

print(tree[0].errors)
print(tree["A"].errors)
print(tree["A"]["B"]["C"].errors)
{}
{}
{'minItems': ValidationError("['spam'] is too short", None, ())}

What I want to say:
1). In this time function ErrorTree is useless for indicate what block of code invoke exception. It return only first name of object in json tree (often json files have only one main object and many child's. So, what favor to return me name of my main object?)
2). There is no way to return tree["A"]["B"]["C"].errors through a program code. I type it by my hands
3). Feature request: Let's tree include all objects in exception pass i.e.

for x in tree:
    print(x)

returned:

0
A
B
C

4). Feature request: Add method to return full path to exception block in json format, Method can return list of all json error path's example:

instance = {
    "A":{
        "X":{},
        "B":{
            "C":["spam"]
        },
        "Y":{}
    }
}
v = Draft3Validator(schema)
tree = ErrorTree(v.iter_errors(instance))
print(tree.ErrorsPath)

return:

[
{"A":{"B":{"C":["spam"]}}}
{"A":{"B":{"C":["spam"]}}}
]
print(tree.ErrorsPath[0])
print(tree.ErrorsPath[0].message)

return:

{"A":{"B":{"C":["spam"]}}}
['spam'] is too short

Validation fails for some code that conforms to json schema

The following script gives this error, but validates with validictory (another validator I tried). I think the "request" conforms to the schema.

Traceback (most recent call last):
File "playpen.py", line 27, in
jsonschema.validate(json.loads(request), create)
File "build\bdist.win32\egg\jsonschema.py", line 740, in validate
File "build\bdist.win32\egg\jsonschema.py", line 419, in validate
jsonschema.ValidationError: [1, 2, 3] is not of type [{'type': ['string', 'number']}, {'items': {'type': ['string', 'number']}, 'type': 'array'}]

script:

import jsonschema
import json

param_atom = {"type": ["string", "number"]}

param_list = {"type": "array", "items": param_atom}

param = {"type": "object", "properties":
{"name": {"type": "string"},
"value": {"type": [param_atom, param_list]}}}

create = {"type": "object", "properties":
{
"params": {"type": "array", "items": param}
}}

request =
'''{
"params": [ {"name": "arg1",
"value": [1,2,3]}]

}'''

jsonschema.validate(json.loads(request), create)

Returning JSON Error Field Name

Hi, thanks for your work! Muchly appreciated. I was wondering if you could add this into your code to return the name of the JSON field where the error was generated, e.g.

def validate_minLength(self, mL, instance, schema):
    if self.is_type(instance, "string") and len(instance) < mL:
        yield ValidationError("%r is too short" % (instance,), errorField=="minLength")

Also we've added the instance key and a more human-readable error message to a returned list of dictionaries containing the error info -- much easier now after your code revisions but could we do a pull request for that?

Thanks again!

Not an issue; but...

Hello,

I am one of the members of the GitHub JSON Schema organization, at https://github.com/json-schema.

This is not an issue, just an informational post that your implementation is listed on the website's implementations page at:

http://json-schema.org/implementations.html

Additionally, this group has taken responsibility to write specifications for the "next generation" JSON Schema, and your input would be appreciated.

Thanks for your time, and your implementation!

additionalProperties checking not properly recursive

The draft spec is a bit confusing, so it is possible that the implementation behaves correctly and that I have simply misunderstood. If so, please close this issue.

Given these schemas:

{
  "properties": {
    "name": {
      "type": "string"
    }
  },
  "additionalProperties": {
    "$ref": "/other"
  }
}

With the referenced '/other' schema being:

{
  "additionalProperties": false
}

I reason that an object containing properties other than "name" should fail validation against the first schema. That isn't the case, currently: referencing other schema via additionalProperties causes all unknown properties to be accepted, regardless of the content of the referenced schema.

Use properties defaults

When using a schema that has some default values for properties, the validation
passes when those properties are missing.

That's completely fine, but I'd expect also that when a property is missing,
the data passed to the validator is overwritten to set the property to the
default value according to the schema.

For example:

>>> schema = {'type': 'object',
              'properties': {
              'answer': {'type': 'integer', 'default': 42},
              },
             }
>>> data = {}
>>> jsonschema.validate(data, schema)
>>> print data
{}

What I'd expect is:

>>> print data
{'answer': 42}

I realize that if the schema type doesn't match a mutable type, this won't work
because the jsonschema.validate won't be able to modify the data in place. In such a
case, maybe a change in the API so that it returns the new data would be fine:

>>> schema = {'type': 'integer',
              'default': 42,
             }
>>> new_data = jsonschema.validate(0, schema)
>>> print new_data
42

More info in ValidationErrors

In my project, I want to create user facing error messages which are friendlier than the default ones. I'm thinking we could attach the instance value, as well as the value for the schema keyword that failed to the ValidationError to facilitate this.

The instance could already be grabbed by walking the path through the instance, but it would be a bit easier if it is already attached.

Optimize extends

See the draft for suggestions, but we can cut down on validating things twice by taking time to combine the two schemas intelligently

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.