##// END OF EJS Templates
Misc style changes, add more docstrings
Jessica B. Hamrick -
Show More
@@ -4,7 +4,7 b' from __future__ import print_function'
4 4 import json
5 5 import os
6 6
7 from IPython.external.jsonschema import Draft3Validator
7 from IPython.external.jsonschema import Draft3Validator, SchemaError
8 8 import IPython.external.jsonpointer as jsonpointer
9 9 from IPython.utils.py3compat import iteritems
10 10
@@ -14,20 +14,36 b' schema_path = os.path.join('
14 14 os.path.split(__file__)[0], "v%d" % nbformat, nbformat_schema)
15 15
16 16
17 def isvalid(nbjson, key='/notebook', verbose=False):
18 errors = validate(nbjson, key=key, verbose=verbose)
17 def isvalid(nbjson, verbose=False):
18 """Checks whether the given notebook JSON conforms to the current
19 notebook format schema. Returns True if the JSON is valid, and
20 False otherwise.
21
22 If `verbose` is set, then print out each error that is detected.
23
24 """
25
26 errors = validate(nbjson, verbose=verbose)
19 27 return errors == 0
20 28
21 29
22 def validate(nbjson, key='/notebook', verbose=False):
30 def validate(nbjson, verbose=False):
31 """Checks whether the given notebook JSON conforms to the current
32 notebook format schema, and returns the number of errors.
33
34 If `verbose` is set, then print out each error that is detected.
35
36 """
37
23 38 # load the schema file
24 39 with open(schema_path, 'r') as fh:
25 40 schema_json = json.load(fh)
26 41
27 42 # resolve internal references
28 43 v3schema = resolve_ref(schema_json)
29 v3schema = jsonpointer.resolve_pointer(v3schema, key)
44 v3schema = jsonpointer.resolve_pointer(v3schema, '/notebook')
30 45
46 # count how many errors there are
31 47 errors = 0
32 48 v = Draft3Validator(v3schema)
33 49 for error in v.iter_errors(nbjson):
@@ -39,9 +55,14 b" def validate(nbjson, key='/notebook', verbose=False):"
39 55
40 56
41 57 def resolve_ref(json, schema=None):
42 """return a json with resolved internal references
58 """Resolve internal references within the given JSON. This essentially
59 means that dictionaries of this form:
60
61 {"$ref": "/somepointer"}
62
63 will be replaced with the resolved reference to `/somepointer`.
64 This only supports local reference to the same JSON file.
43 65
44 only support local reference to the same json
45 66 """
46 67
47 68 if not schema:
@@ -58,10 +79,13 b' def resolve_ref(json, schema=None):'
58 79 elif type(json) is dict:
59 80 resolved = {}
60 81 for key, ref in iteritems(json):
82
61 83 # if the key is equal to $ref, then replace the entire
62 84 # dictionary with the resolved value
63 85 if key == '$ref':
64 assert len(json) == 1
86 if len(json) != 1:
87 raise SchemaError(
88 "objects containing a $ref should only have one item")
65 89 pointer = jsonpointer.resolve_pointer(schema, ref)
66 90 resolved = resolve_ref(pointer, schema=schema)
67 91
General Comments 0
You need to be logged in to leave comments. Login now