validator.py
70 lines
| 1.9 KiB
| text/x-python
|
PythonLexer
|
r13348 | from __future__ import print_function | ||
|
r8519 | #!/usr/bin/env python | ||
# -*- coding: utf8 -*- | ||||
|
r12547 | import json | ||
|
r16330 | import os | ||
|
r8519 | |||
|
r16332 | from IPython.external.jsonschema import Draft3Validator | ||
|
r8525 | import IPython.external.jsonpointer as jsonpointer | ||
|
r13361 | from IPython.utils.py3compat import iteritems | ||
|
r8519 | |||
|
r16330 | |||
from .current import nbformat, nbformat_schema | ||||
|
r16335 | schema_path = os.path.join( | ||
|
r16330 | os.path.split(__file__)[0], "v%d" % nbformat, nbformat_schema) | ||
|
r16335 | def validate(nbjson, key='', verbose=True): | ||
# load the schema file | ||||
with open(schema_path, 'r') as fh: | ||||
schema_json = json.load(fh) | ||||
# resolve internal references | ||||
v3schema = resolve_ref(schema_json) | ||||
v3schema = jsonpointer.resolve_pointer(v3schema, key) | ||||
|
r8519 | errors = 0 | ||
|
r16330 | v = Draft3Validator(v3schema) | ||
|
r8674 | for error in v.iter_errors(nbjson): | ||
|
r8519 | errors = errors + 1 | ||
if verbose: | ||||
print(error) | ||||
|
r16335 | |||
|
r8519 | return errors | ||
|
r16330 | |||
|
r16335 | def resolve_ref(json, schema=None): | ||
|
r8519 | """return a json with resolved internal references | ||
only support local reference to the same json | ||||
""" | ||||
|
r16335 | if not schema: | ||
schema = json | ||||
# if it's a list, resolve references for each item in the list | ||||
|
r8519 | if type(json) is list: | ||
|
r16335 | resolved = [] | ||
|
r8519 | for item in json: | ||
|
r16335 | resolved.append(resolve_ref(item, schema=schema)) | ||
# if it's a dictionary, resolve references for each item in the | ||||
# dictionary | ||||
|
r8519 | elif type(json) is dict: | ||
|
r16335 | resolved = {} | ||
for key, ref in iteritems(json): | ||||
# if the key is equal to $ref, then replace the entire | ||||
# dictionary with the resolved value | ||||
|
r8519 | if key == '$ref': | ||
|
r16335 | assert len(json) == 1 | ||
pointer = jsonpointer.resolve_pointer(schema, ref) | ||||
resolved = resolve_ref(pointer, schema=schema) | ||||
|
r16332 | else: | ||
|
r16335 | resolved[key] = resolve_ref(ref, schema=schema) | ||
# otherwise it's a normal object, so just return it | ||||
|
r16332 | else: | ||
|
r16335 | resolved = json | ||
return resolved | ||||