### Install from PyPI Source: https://json-spec.readthedocs.io/installation.html Use pip to install the package from the Cheese shop. ```bash $ pip install json-spec ``` -------------------------------- ### json move examples Source: https://json-spec.readthedocs.io/cli.html Examples of moving values between JSON pointers. ```bash json move '#/foo/2' --target='#/foo/1' --document-json='{"foo": ["bar", "baz"]}' echo '{"foo": ["bar", "baz"]}' | json move '#/foo/2' --target='#/foo/1' json move '#/foo/2' --target='#/foo/1' --document-file=doc.json json move '#/foo/2' --target='#/foo/1' < doc.json ``` -------------------------------- ### Install from source Source: https://json-spec.readthedocs.io/installation.html Use pip to install the package directly from the GitHub repository. ```bash $ pip install git+https://github.com/johnnoone/jsonspec.git ``` -------------------------------- ### json copy examples Source: https://json-spec.readthedocs.io/cli.html Examples of copying values between JSON pointers. ```bash json copy '#/foo/1' --target='#/foo/2' --document-json='{"foo": ["bar", "baz"]}' echo '{"foo": ["bar", "baz"]}' | json copy '#/foo/1' --target='#/foo/2' json copy '#/foo/1' --target='#/foo/2' --document-file=doc.json json copy '#/foo/1' --target='#/foo/2' < doc.json ``` -------------------------------- ### Define PkgProvider in setup.cfg Source: https://json-spec.readthedocs.io/reference.html Example configuration for autoloading providers using setuptools entry_points. ```ini [entry_points] jsonspec.reference.contributions = spec = jsonspec.misc.providers:SpecProvider ``` -------------------------------- ### json extract examples Source: https://json-spec.readthedocs.io/cli.html Examples of extracting fragments from JSON documents. ```bash json extract '#/foo/1' --document-json='{"foo": ["bar", "baz"]}' echo '{"foo": ["bar", "baz"]}' | json extract '#/foo/1' json extract '#/foo/1' --document-file=doc.json json extract '#/foo/1' < doc.json ``` -------------------------------- ### json add examples Source: https://json-spec.readthedocs.io/cli.html Examples of adding a fragment to a JSON document using various input methods. ```bash json add '#/foo/1' --fragment-file=fragment.json --document-json='{"foo": ["bar", "baz"]}' echo '{"foo": ["bar", "baz"]}' | json add '#/foo/1' --fragment-json='first' json add '#/foo/1' --fragment-file=fragment.json --document-file=doc.json json add '#/foo/1' --fragment-file=fragment.json < doc.json ``` -------------------------------- ### json check examples Source: https://json-spec.readthedocs.io/cli.html Examples of verifying values at specific JSON pointers. ```bash json check '#/foo/1' --fragment-file=fragment.json --document-json='{"foo": ["bar", "baz"]}' echo '{"foo": ["bar", "baz"]}' | json check '#/foo/1' --fragment-file=fragment.json json check '#/foo/1' --fragment-file=fragment.json --document-file=doc.json json check '#/foo/1' --fragment-file=fragment.json < doc.json ``` -------------------------------- ### json replace examples Source: https://json-spec.readthedocs.io/cli.html Examples of replacing values at specific JSON pointers. ```bash json replace '#/foo/1' --fragment-file=fragment.json --document-json='{"foo": ["bar", "baz"]}' echo '{"foo": ["bar", "baz"]}' | json replace '#/foo/1' --fragment-file=fragment.json json replace '#/foo/1' --fragment-file=fragment.json --document-file=doc.json json replace '#/foo/1' --fragment-file=fragment.json < doc.json ``` -------------------------------- ### Set up local development environment Source: https://json-spec.readthedocs.io/contributing.html Sets up a virtual environment and installs the local copy in development mode. ```bash $ mkvirtualenv jsonspec $ cd jsonspec/ $ python setup.py develop ``` -------------------------------- ### FilesystemProvider mapping example Source: https://json-spec.readthedocs.io/reference.html Demonstrates how FilesystemProvider maps directory structures to URI prefixes. ```text my/directory/ foo.json -> my:pref:foo# bar.json -> my:pref:bar# baz/ quux.json -> my:pref:baz/quux# ``` -------------------------------- ### json validate examples Source: https://json-spec.readthedocs.io/cli.html Examples of validating a JSON document against a schema. ```bash json validate --schema-file=schema.json --document-json='{"foo": ["bar", "baz"]}' echo '{"foo": ["bar", "baz"]}' | json validate --schema-file=schema.json json validate --schema-file=schema.json --document-file=doc.json json validate --schema-file=schema.json < doc.json ``` -------------------------------- ### json remove examples Source: https://json-spec.readthedocs.io/cli.html Examples of removing values at specific JSON pointers. ```bash json remove '#/foo/1' --document-json='{"foo": ["bar", "baz"]}' echo '{"foo": ["bar", "baz"]}' | json remove '#/foo/1' json remove '#/foo/1' --document-file=doc.json json remove '#/foo/1' < doc.json ``` -------------------------------- ### Add operation examples Source: https://json-spec.readthedocs.io/operations.html Shows adding or replacing a mapping member and inserting an element into a sequence. ```python # add or replace a mapping operations.add({'foo': 'bar'}, '/baz', 'qux') == { 'baz': 'qux', 'foo': 'bar' } # add into a sequence operations.add(['foo', 'bar'], '/1', 'qux') == ['foo', 'qux', 'bar'] ``` -------------------------------- ### Move operation examples Source: https://json-spec.readthedocs.io/operations.html Shows moving a value into a mapping and moving an array element. ```python # move a value into a mapping operations.move({ 'foo': { 'bar': 'baz', 'waldo': 'fred' }, 'qux': { 'corge': 'grault' } }, '/qux/thud', '/foo/waldo') == { 'foo': { 'bar': 'baz' }, 'qux': { 'corge': 'grault', 'thud': 'fred' } } # move an array element operations.move([ 'all', 'grass', 'cows', 'eat' ], '/3', '/1') == [ 'all', 'cows', 'eat', 'grass' ] ``` -------------------------------- ### JSON Reference Example Source: https://json-spec.readthedocs.io/reference.html An example of a JSON object containing a reference and its resolved state. ```json { "foo": {"$ref": "#/bar"}, "bar": true } ``` ```json { "foo": true, "bar": true } ``` -------------------------------- ### Remove operation examples Source: https://json-spec.readthedocs.io/operations.html Demonstrates removing a member from a mapping and an element from a sequence. ```python # remove a mapping member operations.remove({ 'baz': 'qux', 'foo': 'bar' }, '/baz') == {'foo': 'bar'} # remove a sequence element operations.remove(['bar', 'qux', 'baz'], '/1') == ['bar', 'baz'] ``` -------------------------------- ### Check operation examples Source: https://json-spec.readthedocs.io/operations.html Tests if a value at a target location matches a specified value, returning success or error. ```python # testing a value with success obj = { 'baz': 'qux', 'foo': ['a', 2, 'c'] } assert operations.check(obj, '/baz', 'qux') assert operations.check(obj, '/foo/1', 2) # testing a value with error assert not operations.check({'baz': 'qux'}, '/baz', 'bar') ``` -------------------------------- ### Copy operation example Source: https://json-spec.readthedocs.io/operations.html Copies a value from a specified location to a target location. ```python operations.copy({ 'foo': {'bar': 42}, }, 'baz', '/foo/bar') == { 'foo': {'bar': 42}, 'baz': 42 } ``` -------------------------------- ### Use JSON Spec CLI tools Source: https://json-spec.readthedocs.io/index.html Examples of using the json command-line interface to extract, validate, and modify JSON data. ```bash json extract '#/foo/1' --document-json='{"foo": ["bar", "baz"]}' json validate --schema-file=schema.json < doc.json cat doc.json | json add '#/foo/1' --fragment='{"foo": ["bar", "baz"]}' ``` -------------------------------- ### Move operation example Source: https://json-spec.readthedocs.io/operations.html Demonstrates moving a value from one location to another within a nested dictionary structure. ```python from jsonspec import operations obj = { 'foo': { 'bar': 'baz', 'waldo': 'fred' }, 'qux': { 'corge': 'grault' } } assert operations.move(obj, '/qux/thud', '/foo/waldo') == { 'foo': { 'bar': 'baz' }, 'qux': { 'corge': 'grault', 'thud': 'fred' } } ``` -------------------------------- ### Replace operation example Source: https://json-spec.readthedocs.io/operations.html Replaces the value at a specified target location with a new value. ```python operations.replace({ 'baz': 'qux', 'foo': 'bar' }, '/baz', 'boo') == { 'baz': 'boo', 'foo': 'bar' } ``` -------------------------------- ### ReferenceValidator usage example Source: https://json-spec.readthedocs.io/validators.html Create a ReferenceValidator with a pointer URI and validate an object against it. The validator returns True for a valid object, as shown by the assert statement. ```python >>> validator = ReferenceValidator('http://json-schema.org/geo#', context) >>> assert validator({ >>> 'latitude': 0.0124, >>> 'longitude': 1.2345 >>> }) ``` -------------------------------- ### Resolve JSON reference example Source: https://json-spec.readthedocs.io/reference.html Demonstrates the resolve function behavior where it stops at the first level of reference resolution, as shown by the assertion that the result is the list containing the next reference rather than the final value. ```python value = resolve({ 'foo': {'$ref': '#/bar'}, 'bar': [{'$ref': '#/baz'}], 'baz': 'quux', }, '#/foo') ``` ```python assert value == [{'$ref': '#/baz'}] ``` -------------------------------- ### Draft03Validator usage example Source: https://json-spec.readthedocs.io/validators.html Create a Draft03Validator with a schema and validate an object. The validator returns True for a valid object, as shown by the assert statement. ```python >>> validator = Draft03Validator({'min_length': 4}) >>> assert validator('this is sparta') ``` -------------------------------- ### Validate JSON with Python Source: https://json-spec.readthedocs.io/index.html Example of using the jsonspec.validators module to load a schema and validate a data object. ```python from jsonspec.validators import load # data will validate against this schema validator = load({ 'type': 'object', 'properties': { 'firstName': { 'type': 'string', }, 'lastName': { 'type': 'string', }, 'age': { 'type': 'integer' } }, 'required': ['firstName', 'lastName', 'age'] }) # validate this data validator.validate({ 'firstName': 'John', 'lastName': 'Noone', 'age': 33, }) ``` -------------------------------- ### reference.providers.PkgProvider Source: https://json-spec.readthedocs.io/reference.html Provider that autoloads providers declared into setuptools entry_points. ```APIDOC ## reference.providers.PkgProvider ### Description Autoload providers declared into setuptools entry_points. ### Constructor `PkgProvider(namespace=None, configuration=None)` ### Parameters - **namespace** (optional) - Namespace for entry points. - **configuration** (optional) - Configuration for the provider. ### Example ``` [entry_points] jsonspec.reference.contributions = spec = jsonspec.misc.providers:SpecProvider ``` ``` -------------------------------- ### Using FileSystemProvider for JSON References Source: https://json-spec.readthedocs.io/reference.html Shows how to use FileSystemProvider to resolve references to documents stored on the filesystem. ```python from jsonspec.reference import Registry from jsonspec.reference.providers import FileSystemProvider obj = { 'foo': {'$ref': 'my:doc#/sub'} } provider = FileSystemProvider('/path/to/my/doc', prefix='my:doc') resolve(obj, '#/foo/2', { 'obj2': {'sub': 'quux'} }) ``` -------------------------------- ### reference.providers.FilesystemProvider Source: https://json-spec.readthedocs.io/reference.html Provider that exposes JSON documents stored in the filesystem. ```APIDOC ## reference.providers.FilesystemProvider ### Description Exposes JSON documents stored in the filesystem. ### Constructor `FilesystemProvider(directory, prefix=None)` ### Parameters - **directory** (string) - The directory containing the JSON documents. - **prefix** (string, optional) - A prefix to prepend to the document URIs. ### Example With `prefix=my:pref:` and `directory=my/directory`, the filesystem will be loaded as: ``` my/directory/ foo.json -> my:pref:foo# bar.json -> my:pref:bar# baz/ quux.json -> my:pref:baz/quux# ``` ``` -------------------------------- ### Register custom format via entry_points Source: https://json-spec.readthedocs.io/validators.html Registers a custom format validator via entry_points in setup.py. The format name is 'my:format' and the validation function is 'validate_format' in module 'my.module'. ```ini [entry_points] jsonspec.validators.formats = my:format = my.module:validate_format ``` -------------------------------- ### Create a feature branch Source: https://json-spec.readthedocs.io/contributing.html Creates a new branch for your changes. ```bash $ git checkout -b name-of-your-bugfix-or-feature ``` -------------------------------- ### json add usage Source: https://json-spec.readthedocs.io/cli.html Usage syntax for the json add command. ```bash json add [-h] [--document-json | --document-file ] [--fragment-json | --fragment-file ] [--indent ] ``` -------------------------------- ### stage(obj, parent=None, member=None) Source: https://json-spec.readthedocs.io/pointer.html Prepares an object to be staged, primarily used for relative JSON Pointers. Returns a staged document that can be used with relative pointers. ```APIDOC ## stage(obj, parent=None, member=None) ### Description Prepare obj to be staged. This is almost used for relative JSON Pointers. ### Parameters - **obj** (object) - Required - The object to stage - **parent** (object) - Optional - The parent object - **member** (str) - Optional - The member name ### Returns Staged object. ### Example ```python from jsonspec.pointer import extract, stage staged_doc = stage({'foo': ['bar', 'baz'], 'highly': {'nested': {'objects': True}}}) baz_relative = extract(staged_doc, '/foo/1') assert extract(baz_relative, '0') == 'baz' ``` ``` -------------------------------- ### Run a subset of tests Source: https://json-spec.readthedocs.io/contributing.html Runs a subset of tests using the unittest module. ```bash $ python -m unittest tests.test_jsonspec ``` -------------------------------- ### Run flake8, tests, and tox Source: https://json-spec.readthedocs.io/contributing.html Runs flake8, the test suite, and tox to verify changes across supported Python versions. ```bash $ flake8 jsonspec tests $ python setup.py test $ tox ``` -------------------------------- ### class reference.Registry(provider=None) Source: https://json-spec.readthedocs.io/reference.html Registers all documents. The provider can be a Provider or dict containing all documents. ```APIDOC ## class reference.Registry(provider=None) ### Description Register all documents. The provider can be a Provider or dict containing all documents. ### Constructor Parameters - **provider** (Provider, dict) - Optional - All documents. ### Methods #### resolve(pointer) Resolve from documents. ##### Parameters - **pointer** (DocumentPointer) - Required - The pointer to resolve. ``` -------------------------------- ### Register a compiler with register() function Source: https://json-spec.readthedocs.io/validators.html Use the register function as a regular function to expose a custom compiler for a specific spec name. The compiler receives schema, pointer, and context and must return a Validator instance. ```python def my_compiler(schema, pointer, context): return Validator(schema) register(my_compiler, 'my:second:spec') ``` -------------------------------- ### class reference.LocalRegistry(doc, provider=None) Source: https://json-spec.readthedocs.io/reference.html Scoped registry to a local document. The doc is the local document, provider contains all documents, and key is the current document identifier. ```APIDOC ## class reference.LocalRegistry(doc, provider=None) ### Description Scoped registry to a local document. The doc is the local document, provider contains all documents, and key is the current document identifier. ### Constructor Parameters - **doc** (object) - Required - The local document. - **provider** (Provider, dict) - Optional - All documents. ### Variables - **doc** - The local document. - **provider** - All documents. - **key** - Current document identifier. ``` -------------------------------- ### json move usage Source: https://json-spec.readthedocs.io/cli.html Usage syntax for the json move command. ```bash json move [-h] [--document-json | --document-file ] [-t ] [--indent ] ``` -------------------------------- ### json copy usage Source: https://json-spec.readthedocs.io/cli.html Usage syntax for the json copy command. ```bash json copy [-h] [--document-json | --document-file ] [-t ] [--indent ] ``` -------------------------------- ### Iterating through Pointer tokens Source: https://json-spec.readthedocs.io/pointer.html Shows how to extract a value by iterating through the tokens of a `Pointer` object. ```python obj = document for token in Pointer('/foo/1'): obj = token.extract(obj) assert 'baz' == obj ``` -------------------------------- ### Resolving JSON References with jsonspec Source: https://json-spec.readthedocs.io/reference.html Demonstrates the simplest way to resolve JSON references using the resolve function. ```python from jsonspec.reference import resolve obj = { 'foo': ['bar', {'$ref': '#/sub'}, {'$ref': 'obj2#/sub'}], 'sub': 'baz' } assert 'bar' == resolve(obj, '#/foo/0') assert 'baz' == resolve(obj, '#/foo/1') assert 'quux' == resolve(obj, '#/foo/2', { 'obj2': {'sub': 'quux'} }) ``` -------------------------------- ### operations.copy(doc, dest, src) Source: https://json-spec.readthedocs.io/operations.html Copies an element from a source location to a destination location. Returns the new object. ```APIDOC ## operations.copy(doc, dest, src) ### Description Copy element from sequence, member from mapping. ### Method Function ### Signature `operations.copy(doc, dest, src)` ### Parameters - **doc** - The document base. - **dest** (Pointer) - The destination. - **src** (Pointer) - The source. ### Returns - **object** - The new object. ``` -------------------------------- ### Mix draft04 and draft03 specifications in one schema Source: https://json-spec.readthedocs.io/validators.html Loads a schema where the inner schema specifies draft03 via its '$schema' property while the outer schema uses the default draft04. The outer schema is parsed with draft04 and the inner with draft03. ```python validator = load({ 'id': 'foo', 'properties': { 'bar': { '$schema': 'http://json-schema.org/draft-03/schema#', 'id': 'baz' }, }, }) ``` -------------------------------- ### validators.load Source: https://json-spec.readthedocs.io/validators.html Scaffold a validator against a schema. This function takes a schema and optional parameters to create a validator instance. ```APIDOC ## `validators.load` ### Description Scaffold a validator against a schema. ### Parameters - **schema** (Mapping) - Required - The schema to compile into a Validator - **uri** (Pointer, str) - Optional - The uri of the schema. It may be ignored in case of not cross referencing. - **spec** (str) - Optional - Fallback to this spec if the schema does not provide its own - **provider** (Mapping, Provider...) - Optional - The other schemas, in case of cross referencing ``` -------------------------------- ### Relative JSON Pointer with stage function Source: https://json-spec.readthedocs.io/pointer.html Shows how to convert a document into a staged document and extract values using relative JSON Pointer syntax, including tests for staged objects, keys, and unstaged objects. ```python from jsonspec.pointer import extract, stage staged_doc = stage({ 'foo': ['bar', 'baz'], 'highly': { 'nested': { 'objects': True } } }) baz_relative = extract(self.document, '/foo/1') # staged objects assert extract(baz_relative, '0') == 'baz' assert extract(baz_relative, '1/0') == 'bar' assert extract(baz_relative, '2/highly/nested/objects') == True # `foo is True` won't work # keys, not staged assert extract(baz_relative, '0#') == 1 assert extract(baz_relative, '1#') == 'foo' # unstage object assert extract(baz_relative, '0').obj == 'baz' assert extract(baz_relative, '1/0').obj == 'bar' assert extract(baz_relative, '2/highly/nested/objects').obj is True ``` -------------------------------- ### reference.NotFound Source: https://json-spec.readthedocs.io/reference.html Exception raised when a document is not found. ```APIDOC ## reference.NotFound ### Description Exception raised when a document is not found. ### Exception `reference.NotFound` ``` -------------------------------- ### Basic extraction with extract and Pointer Source: https://json-spec.readthedocs.io/pointer.html Defines a JSON document and extracts a value using the `extract` function and the `Pointer` class with the pointer string '/foo/1'. ```python from jsonspec.pointer import extract, Pointer document = { 'foo': ['bar', 'baz', { '$ref': 'obj2#/sub' }] } assert 'baz' == extract(document, '/foo/1') ``` -------------------------------- ### operations.move(doc, dest, src) Source: https://json-spec.readthedocs.io/operations.html Moves an element from a source location to a destination location. Returns the new object. ```APIDOC ## operations.move(doc, dest, src) ### Description Move element from sequence, member from mapping. ### Method Function ### Signature `operations.move(doc, dest, src)` ### Parameters - **doc** - The document base. - **dest** (Pointer) - The destination. - **src** (Pointer) - The source. ### Returns - **object** - The new object. ### Note It deletes then it adds to the new location so the dest must refer to the middle object. ``` -------------------------------- ### class reference.util.Mapping Source: https://json-spec.readthedocs.io/reference.html A generic container for associating key/value pairs. Provides concrete generic implementations of all methods except for __getitem__, __iter__, and __len__. ```APIDOC ## class reference.util.Mapping ### Description A Mapping is a generic container for associating key/value pairs. This class provides concrete generic implementations of all methods except for __getitem__, __iter__, and __len__. ### Methods #### get(k[, d]) Return D[k] if k in D, else d. d defaults to None. #### items() Return list of D's (key, value) pairs, as 2-tuples. #### iteritems() Return an iterator over the (key, value) items of D. #### iterkeys() Return an iterator over the keys of D. #### itervalues() Return an iterator over the values of D. #### keys() Return list of D's keys. #### values() Return list of D's values. ``` -------------------------------- ### json replace usage Source: https://json-spec.readthedocs.io/cli.html Usage syntax for the json replace command. ```bash json replace [-h] [--document-json | --document-file ] [--fragment-json | --fragment-file ] [--indent ] ``` -------------------------------- ### reference.providers.SpecProvider Source: https://json-spec.readthedocs.io/reference.html Provider that provides specs of http://json-schema.org/. ```APIDOC ## reference.providers.SpecProvider ### Description Provides specs of http://json-schema.org/. ``` -------------------------------- ### reference.resolve(obj, pointer, registry=None) Source: https://json-spec.readthedocs.io/reference.html Resolves a local object using a JSON pointer. The pointer can be a DocumentPointer or a string. The registry is optional and can be a Provider or dict, used when inner references refer to other documents. ```APIDOC ## reference.resolve(obj, pointer, registry=None) ### Description Resolve a local object using a JSON pointer. The pointer can be a DocumentPointer or a string. The registry is optional and can be a Provider or dict, used when inner references refer to other documents. ### Parameters - **obj** (object) - Required - The local object to resolve. - **pointer** (DocumentPointer, str) - Required - The pointer to resolve. - **registry** (Provider, dict) - Optional - The registry. It may be omitted if inner JSON references in the document don't refer to other documents. ### Warning Once pointer is extracted, it won't follow sub mapping/element. For example, the value of: ``` value = resolve({ 'foo': {'$ref': '#/bar'}, 'bar': [{'$ref': '#/baz'}], 'baz': 'quux', }, '#/foo') ``` is: ``` assert value == [{'$ref': '#/baz'}] ``` and not: ``` assert value == ['quux'] ``` ``` -------------------------------- ### Target.copy(dest, src) Source: https://json-spec.readthedocs.io/operations.html Copies an element from a source location to a destination location. Returns the resolved document as a Target. ```APIDOC ## Target.copy(dest, src) ### Description Copy element from sequence, member from mapping. ### Method Method ### Signature `Target.copy(dest, src)` ### Parameters - **dest** (Pointer) - The destination. - **src** (Pointer) - The source. ### Returns - **Target** - Resolved document. ``` -------------------------------- ### Commit and push changes Source: https://json-spec.readthedocs.io/contributing.html Commits and pushes your changes to the remote branch. ```bash $ git add . $ git commit -m "Your detailed description of your changes." $ git push origin name-of-your-bugfix-or-feature ``` -------------------------------- ### json check usage Source: https://json-spec.readthedocs.io/cli.html Usage syntax for the json check command. ```bash json check [-h] [--document-json | --document-file ] [--fragment-json | --fragment-file ] ``` -------------------------------- ### operations.add(doc, pointer, value) Source: https://json-spec.readthedocs.io/operations.html Adds an element to a sequence or a member to a mapping at the specified pointer. Returns the new object. ```APIDOC ## operations.add(doc, pointer, value) ### Description Add element to sequence, member to mapping. ### Method Function ### Signature `operations.add(doc, pointer, value)` ### Parameters - **doc** - The document base. - **pointer** - The path to add in it. - **value** - The new value. ### Returns - **object** - The new object. ``` -------------------------------- ### Target.move(dest, src) Source: https://json-spec.readthedocs.io/operations.html Moves an element from a source location to a destination location. Returns the resolved document as a Target. ```APIDOC ## Target.move(dest, src) ### Description Move element from sequence, member from mapping. ### Method Method ### Signature `Target.move(dest, src)` ### Parameters - **dest** (Pointer) - The destination. - **src** (Pointer) - The source. ### Returns - **Target** - Resolved document. ### Note This operation is functionally identical to a “remove” operation on the “from” location, followed immediately by an “add” operation at the target location with the value that was just removed. The “from” location MUST NOT be a proper prefix of the “path” location; i.e., a location cannot be moved into one of its children. ``` -------------------------------- ### Clone the jsonspec repository Source: https://json-spec.readthedocs.io/contributing.html Clones the forked jsonspec repository from GitHub to your local machine. ```bash $ git clone git@github.com:your_name_here/jsonspec.git ``` -------------------------------- ### Target.add(pointer, value) Source: https://json-spec.readthedocs.io/operations.html Adds an element to a sequence or a member to a mapping at the specified pointer. Returns the resolved document as a Target. ```APIDOC ## Target.add(pointer, value) ### Description Add element to sequence, member to mapping. ### Method Method ### Signature `Target.add(pointer, value)` ### Parameters - **pointer** - The path to add in it. - **value** - The new value. ### Returns - **Target** - Resolved document. ### Details The pointer must reference one of: - The root of the target document - whereupon the specified value becomes the entire content of the target document. - A member to add to an existing mapping - whereupon the supplied value is added to that mapping at the indicated location. If the member already exists, it is replaced by the specified value. - An element to add to an existing sequence - whereupon the supplied value is added to the sequence at the indicated location. Any elements at or above the specified index are shifted one position to the right. The specified index must not be greater than the number of elements in the sequence. If the “-” character is used to index the end of the sequence, this has the effect of appending the value to the sequence. ``` -------------------------------- ### Load schema with draft03 specification Source: https://json-spec.readthedocs.io/validators.html Loads a schema with nested 'id' properties using the draft03 specification explicitly. Both the outer and inner schemas are parsed with draft03. ```python validator = load({ 'id': 'foo', 'properties': { 'bar': { 'id': 'baz' }, }, }, spec='http://json-schema.org/draft-03/schema#') ``` -------------------------------- ### Load schema with default draft04 specification Source: https://json-spec.readthedocs.io/validators.html Loads a schema with nested 'id' properties using the default draft04 specification. Both the outer and inner schemas are parsed with draft04. ```python validator = load({ 'id': 'foo', 'properties': { 'bar': { 'id': 'baz' }, }, }) ``` -------------------------------- ### reference.Forbidden Source: https://json-spec.readthedocs.io/reference.html Exception raised when trying to replace a local document. ```APIDOC ## reference.Forbidden ### Description Exception raised when trying to replace a local document. ### Exception `reference.Forbidden` ``` -------------------------------- ### Register a compiler with @register decorator Source: https://json-spec.readthedocs.io/validators.html Use the register function as a decorator to expose a custom compiler for a specific spec name. The compiler receives schema, pointer, and context and must return a Validator instance. ```python @register(spec='my:first:spec') def my_compiler(schema, pointer, context): return Validator(schema) ``` -------------------------------- ### json replace Source: https://json-spec.readthedocs.io/cli.html Replaces the value at a specified location with a new fragment. ```APIDOC ## json replace ### Description Replaces the value at a specified location with a new fragment. ### Usage ``` json replace [-h] [--document-json | --document-file ] [--fragment-json | --fragment-file ] [--indent ] ``` ### Parameters - **pointer** (string) - Required - JSON Pointer indicating the location to replace. - **--document-json** (string) - Optional - JSON document as a string. - **--document-file** (string) - Optional - Path to a file containing the JSON document. - **--fragment-json** (string) - Optional - JSON fragment as a string. - **--fragment-file** (string) - Optional - Path to a file containing the JSON fragment. - **--indent** (string) - Optional - Indentation for output. ### Examples ``` json replace '#/foo/1' --fragment-file=fragment.json --document-json='{"foo": ["bar", "baz"]}' echo '{"foo": ["bar", "baz"]}' | json replace '#/foo/1' --fragment-file=fragment.json json replace '#/foo/1' --fragment-file=fragment.json --document-file=doc.json json replace '#/foo/1' --fragment-file=fragment.json < doc.json ``` ``` -------------------------------- ### json extract usage Source: https://json-spec.readthedocs.io/cli.html Usage syntax for the json extract command. ```bash json extract [-h] [--document-json | --document-file ] [--indent ] ``` -------------------------------- ### json add Source: https://json-spec.readthedocs.io/cli.html Transforms a JSON document by adding a fragment at the specified pointer location. ```APIDOC ## json add ### Description Transform a json document by adding a fragment at the specified pointer. ### Usage ``` json add [-h] [--document-json | --document-file ] [--fragment-json | --fragment-file ] [--indent ] ``` ### Parameters - **pointer** (string) - Required - JSON Pointer indicating where to add the fragment. - **--document-json** (string) - Optional - JSON document as a string. - **--document-file** (string) - Optional - Path to a file containing the JSON document. - **--fragment-json** (string) - Optional - JSON fragment as a string. - **--fragment-file** (string) - Optional - Path to a file containing the JSON fragment. - **--indent** (string) - Optional - Indentation for output. ### Examples ``` json add '#/foo/1' --fragment-file=fragment.json --document-json='{"foo": ["bar", "baz"]}' echo '{"foo": ["bar", "baz"]}' | json add '#/foo/1' --fragment-json='first' json add '#/foo/1' --fragment-file=fragment.json --document-file=doc.json json add '#/foo/1' --fragment-file=fragment.json < doc.json ``` ``` -------------------------------- ### json validate usage Source: https://json-spec.readthedocs.io/cli.html Usage syntax for the json validate command. ```bash json validate [-h] [--document-json | --document-file ] [--schema-json | --schema-file ] [--indent ] ``` -------------------------------- ### validators.Context Source: https://json-spec.readthedocs.io/validators.html Context class that holds the factory, registry, spec, and formats for validation. ```APIDOC ## `validators.Context` ### Description Represents the context for validation. ### Attributes - **factory** - Global factory - **registry** - The current registry - **spec** - The current spec - **formats** - The current formats exposed ``` -------------------------------- ### Exceptions Source: https://json-spec.readthedocs.io/pointer.html Exception classes raised by the pointer module for various error conditions during extraction. ```APIDOC ## Exceptions ### ExtractError(obj, *args) Raised for any errors. **Attributes:** - **obj** - The object that raised this event ### RefError(obj, *args) Raised when encountered a JSON Ref. **Attributes:** - **obj** - The object that raised this event ### LastElement(obj, *args) Raised when refers to the last element of a sequence. **Attributes:** - **obj** - The object that raised this event ### OutOfBounds(obj, *args) Raised when a member of a mapping does not exist. **Attributes:** - **obj** - The object that raised this event ### OutOfRange(obj, *args) Raised when an element of a sequence does not exist. **Attributes:** - **obj** - The object that raised this event ``` -------------------------------- ### Bypassing JSON Reference error with bypass_ref Source: https://json-spec.readthedocs.io/pointer.html Demonstrates using `bypass_ref=True` to extract a JSON Reference value ('$ref') without raising a `RefError`. ```python assert 'obj2#/sub' == extract(document, '/foo/2/$ref', bypass_ref=True) ``` -------------------------------- ### json copy Source: https://json-spec.readthedocs.io/cli.html Copies the value at a specified location to the target location. ```APIDOC ## json copy ### Description Copies the value at a specified location to the target location. ### Usage ``` json copy [-h] [--document-json | --document-file ] [-t ] [--indent ] ``` ### Parameters - **pointer** (string) - Required - JSON Pointer indicating the source location. - **--target** or **-t** (string) - Optional - JSON Pointer indicating the target location. - **--document-json** (string) - Optional - JSON document as a string. - **--document-file** (string) - Optional - Path to a file containing the JSON document. - **--indent** (string) - Optional - Indentation for output. ### Examples ``` json copy '#/foo/1' --target='#/foo/2' --document-json='{"foo": ["bar", "baz"]}' echo '{"foo": ["bar", "baz"]}' | json copy '#/foo/1' --target='#/foo/2' json copy '#/foo/1' --target='#/foo/2' --document-file=doc.json json copy '#/foo/1' --target='#/foo/2' < doc.json ``` ``` -------------------------------- ### class reference.util.MutableMapping Source: https://json-spec.readthedocs.io/reference.html A MutableMapping is a generic container for associating key/value pairs. Provides concrete generic implementations of all methods except for __getitem__, __setitem__, __delitem__, __iter__, and __len__. ```APIDOC ## class reference.util.MutableMapping ### Description A MutableMapping is a generic container for associating key/value pairs. This class provides concrete generic implementations of all methods except for __getitem__, __setitem__, __delitem__, __iter__, and __len__. ### Methods #### clear() Remove all items from D. #### pop(k[, d]) Remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. #### popitem() Remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. #### setdefault(k[, d]) Return D.get(k,d), also set D[k]=d if k not in D. #### update([E, ]**F) Update D from mapping/iterable E and F. If E present and has a .keys() method, does: for k in E: D[k] = E[k]. If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v. In either case, this is followed by: for k, v in F.items(): D[k] = v. ``` -------------------------------- ### Target.check(pointer, expected, raise_onerror=False) Source: https://json-spec.readthedocs.io/operations.html Checks if a value exists at the specified pointer in the document. Returns a boolean. ```APIDOC ## Target.check(pointer, expected, raise_onerror=False) ### Description Check if value exists into object. ### Method Method ### Signature `Target.check(pointer, expected, raise_onerror=False)` ### Parameters - **pointer** - The path to search in. - **expected** - The expected value. - **raise_onerror** (bool) - Should raise on error? Default: False. ### Returns - **boolean** - True if the value exists and matches expected, False otherwise. ``` -------------------------------- ### Incorrect resolution expectation Source: https://json-spec.readthedocs.io/reference.html Shows the result that is NOT produced by the resolve function, illustrating that sub-mapping is not followed automatically. ```python assert value == ['quux'] ``` -------------------------------- ### json remove usage Source: https://json-spec.readthedocs.io/cli.html Usage syntax for the json remove command. ```bash json remove [-h] [--document-json | --document-file ] [--indent ] ``` -------------------------------- ### operations.replace(doc, pointer, value) Source: https://json-spec.readthedocs.io/operations.html Replaces an element in a sequence or a member in a mapping at the specified pointer. Returns the new object. ```APIDOC ## operations.replace(doc, pointer, value) ### Description Replace element from sequence, member from mapping. ### Method Function ### Signature `operations.replace(doc, pointer, value)` ### Parameters - **doc** - The document base. - **pointer** - The path to search in. - **value** - The new value. ### Returns - **object** - The new object. ### Note This operation is functionally identical to a “remove” operation for a value, followed immediately by an “add” operation at the same location with the replacement value. ``` -------------------------------- ### Target.replace(pointer, value) Source: https://json-spec.readthedocs.io/operations.html Replaces an element in a sequence or a member in a mapping at the specified pointer. Returns the resolved document as a Target. ```APIDOC ## Target.replace(pointer, value) ### Description Replace element from sequence, member from mapping. ### Method Method ### Signature `Target.replace(pointer, value)` ### Parameters - **pointer** - The path to search in. - **value** - The new value. ### Returns - **Target** - Resolved document. ``` -------------------------------- ### json move Source: https://json-spec.readthedocs.io/cli.html Removes the value at a specified location and adds it to the target location. ```APIDOC ## json move ### Description Removes the value at a specified location and adds it to the target location. ### Usage ``` json move [-h] [--document-json | --document-file ] [-t ] [--indent ] ``` ### Parameters - **pointer** (string) - Required - JSON Pointer indicating the source location. - **--target** or **-t** (string) - Optional - JSON Pointer indicating the target location. - **--document-json** (string) - Optional - JSON document as a string. - **--document-file** (string) - Optional - Path to a file containing the JSON document. - **--indent** (string) - Optional - Indentation for output. ### Examples ``` json move '#/foo/2' --target='#/foo/1' --document-json='{"foo": ["bar", "baz"]}' echo '{"foo": ["bar", "baz"]}' | json move '#/foo/2' --target='#/foo/1' json move '#/foo/2' --target='#/foo/1' --document-file=doc.json json move '#/foo/2' --target='#/foo/1' < doc.json ``` ``` -------------------------------- ### Basic validation with jsonspec.validators.load Source: https://json-spec.readthedocs.io/validators.html Loads a JSON Schema and validates a data object against it. The schema requires 'firstName' and 'lastName' and validates 'age' as a non-negative integer. ```python from jsonspec.validators import load # data will validate against this schema validator = load({ 'title': 'Example Schema', 'type': 'object', 'properties': { 'age': { 'description': 'Age in years', 'minimum': 0, 'type': 'integer' }, 'firstName': { 'type': 'string' }, 'lastName': { 'type': 'string' } }, 'required': [ 'firstName', 'lastName' ] }) # validate this data validator.validate({ 'firstName': 'John', 'lastName': 'Noone', 'age': 33, }) ``` -------------------------------- ### DocumentPointer(pointer) Source: https://json-spec.readthedocs.io/pointer.html Defines a document pointer that includes a document name and a pointer. Provides methods to extract values, check if the pointer refers to an inner document, and support os.path.join. ```APIDOC ## class DocumentPointer(pointer) ### Description Defines a document pointer. ### Constructor Parameters - **pointer** (str) - Required - The pointer string ### Attributes - **document** - Document name - **pointer** - Pointer ### Methods #### endswith(txt) Used by os.path.join. **Parameters:** - **txt** (str) - Required - The suffix to check #### extract(obj, bypass_ref=False) Extract subelement from obj, according to pointer. It assumes that document is the object. **Parameters:** - **obj** (object) - Required - The object source - **bypass_ref** (boolean) - Optional - Disable JSON Reference errors #### is_inner() Tells if pointer refers to an inner document. **Returns:** Boolean indicating if the pointer is inner. ``` -------------------------------- ### validators.Factory Source: https://json-spec.readthedocs.io/validators.html Factory class that manages the global registry and default spec for validator creation. ```APIDOC ## `validators.Factory` ### Description Factory class for creating validators. ### Attributes - **provider** - Global registry - **spec** - Default spec ``` -------------------------------- ### validators.register Source: https://json-spec.readthedocs.io/validators.html Registers a compiler with the factory. Can be used as a decorator or as a function to expose a custom compiler for a specific spec. ```APIDOC ## `validators.register` ### Description Expose compiler to factory. Can be used as a decorator or as a function. ### Parameters - **compiler** (callable) - Optional - The callable to expose - **spec** (str) - Optional - Name of the spec ### Usage Example ```python @register(spec='my:first:spec') def my_compiler(schema, pointer, context): return Validator(schema) ``` or as a function: ```python def my_compiler(schema, pointer, context): return Validator(schema) register(my_compiler, 'my:second:spec') ``` ``` -------------------------------- ### Pointer(pointer) Source: https://json-spec.readthedocs.io/pointer.html Defines a pointer object that can be iterated to extract values from a JSON document. Provides an extract method to retrieve subelements based on the pointer tokens. ```APIDOC ## class Pointer(pointer) ### Description Defines a pointer. Can be iterated to extract values from a JSON document. ### Constructor Parameters - **pointer** (str) - Required - The pointer string ### Attributes - **tokens** (list of PointerToken) - The parsed tokens ### Methods #### extract(obj, bypass_ref=False) Extract subelement from obj, according to tokens. **Parameters:** - **obj** (object) - Required - The object source - **bypass_ref** (boolean) - Optional - Disable JSON Reference errors **Returns:** Extracted value. #### parse(pointer) Parse pointer into tokens. **Parameters:** - **pointer** (str) - Required - The pointer string ### Example ```python from jsonspec.pointer import Pointer document = {'foo': ['bar', 'baz']} obj = document for token in Pointer('/foo/1'): obj = token.extract(obj) assert 'baz' == obj ``` ```