pax_global_header00006660000000000000000000000064132274137020014513gustar00rootroot0000000000000052 comment=8d8629a82fbebf5104f6e8fc37f4eb7ed5ce9021 python-json-pointer-2.0/000077500000000000000000000000001322741370200153225ustar00rootroot00000000000000python-json-pointer-2.0/.coveragerc000066400000000000000000000004561322741370200174500ustar00rootroot00000000000000# .coveragerc to control coverage.py [run] branch = True [report] # Regexes for lines to exclude from consideration exclude_lines = # Have to re-enable the standard pragma pragma: no cover # No need to test __repr__ def __repr__ # Python 2/3 compatibility except ImportError python-json-pointer-2.0/.gitignore000066400000000000000000000001001322741370200173010ustar00rootroot00000000000000*.pyc build .coverage MANIFEST dist *.swp doc/_build *.egg-info python-json-pointer-2.0/.travis.yml000066400000000000000000000011631322741370200174340ustar00rootroot00000000000000language: python python: - '2.7' - '3.4' - '3.5' - '3.6' - 3.6-dev - 3.7-dev - nightly - pypy - pypy3 install: - travis_retry pip install coveralls script: - coverage run --source=jsonpointer tests.py after_script: - coveralls sudo: false addons: apt: packages: - pandoc before_deploy: - pip install -r requirements-dev.txt deploy: provider: pypi user: skoegl password: secure: bKET/1sK+uWetPM3opPTt4qHHfZ6bMcjuLGe3Z/EUfNnGazcbDezy9CHJSqofuMXynF3xc8yluEojjfaqos3Ge/Y4o8pdFMY8ABp8KkxMnAJYGtYzbneSHgdgxPKsmdcUMVtIfioqkeNJTJClWUhRikWSlpKZ7TtkK4AmWtKNwc= on: tags: true distributions: sdist bdist_wheel python-json-pointer-2.0/AUTHORS000066400000000000000000000001611322741370200163700ustar00rootroot00000000000000Stefan Kögl Alexander Shorin Christopher J. White python-json-pointer-2.0/LICENSE.txt000066400000000000000000000026051322741370200171500ustar00rootroot00000000000000Copyright (c) 2011 Stefan Kögl All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. python-json-pointer-2.0/MANIFEST.in000066400000000000000000000001071322741370200170560ustar00rootroot00000000000000include AUTHORS include LICENSE.txt include README.md include tests.py python-json-pointer-2.0/README.md000066400000000000000000000022171322741370200166030ustar00rootroot00000000000000python-json-pointer =================== [![PyPI version](https://img.shields.io/pypi/v/jsonpointer.svg)](https://pypi.python.org/pypi/jsonpointer/) [![Supported Python versions](https://img.shields.io/pypi/pyversions/jsonpointer.svg)](https://pypi.python.org/pypi/jsonpointer/) [![Build Status](https://travis-ci.org/stefankoegl/python-json-pointer.png?branch=master)](https://travis-ci.org/stefankoegl/python-json-pointer) [![Coverage Status](https://coveralls.io/repos/stefankoegl/python-json-pointer/badge.png?branch=master)](https://coveralls.io/r/stefankoegl/python-json-pointer?branch=master) Resolve JSON Pointers in Python ------------------------------- Library to resolve JSON Pointers according to [RFC 6901](http://tools.ietf.org/html/rfc6901) See source code for examples * Website: https://github.com/stefankoegl/python-json-pointer * Repository: https://github.com/stefankoegl/python-json-pointer.git * Documentation: https://python-json-pointer.readthedocs.org/ * PyPI: https://pypi.python.org/pypi/jsonpointer * Travis CI: https://travis-ci.org/stefankoegl/python-json-pointer * Coveralls: https://coveralls.io/r/stefankoegl/python-json-pointer python-json-pointer-2.0/bin/000077500000000000000000000000001322741370200160725ustar00rootroot00000000000000python-json-pointer-2.0/bin/jsonpointer000077500000000000000000000034601322741370200203750ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import sys import os.path import json import jsonpointer import argparse parser = argparse.ArgumentParser( description='Resolve a JSON pointer on JSON files') # Accept pointer as argument or as file ptr_group = parser.add_mutually_exclusive_group(required=True) ptr_group.add_argument('-f', '--pointer-file', type=argparse.FileType('r'), nargs='?', help='File containing a JSON pointer expression') ptr_group.add_argument('POINTER', type=str, nargs='?', help='A JSON pointer expression') parser.add_argument('FILE', type=argparse.FileType('r'), nargs='+', help='Files for which the pointer should be resolved') parser.add_argument('--indent', type=int, default=None, help='Indent output by n spaces') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + jsonpointer.__version__) def main(): try: resolve_files() except KeyboardInterrupt: sys.exit(1) def parse_pointer(args): if args.POINTER: ptr = args.POINTER elif args.pointer_file: ptr = args.pointer_file.read().strip() else: parser.print_usage() sys.exit(1) return ptr def resolve_files(): """ Resolve a JSON pointer on JSON files """ args = parser.parse_args() ptr = parse_pointer(args) for f in args.FILE: doc = json.load(f) try: result = jsonpointer.resolve_pointer(doc, ptr) print(json.dumps(result, indent=args.indent)) except jsonpointer.JsonPointerException as e: print('Could not resolve pointer: %s' % str(e), file=sys.stderr) if __name__ == "__main__": main() python-json-pointer-2.0/doc/000077500000000000000000000000001322741370200160675ustar00rootroot00000000000000python-json-pointer-2.0/doc/Makefile000066400000000000000000000127601322741370200175350ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-json-pointer.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-json-pointer.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/python-json-pointer" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python-json-pointer" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." python-json-pointer-2.0/doc/_static/000077500000000000000000000000001322741370200175155ustar00rootroot00000000000000python-json-pointer-2.0/doc/_static/.empty000066400000000000000000000000001322741370200206420ustar00rootroot00000000000000python-json-pointer-2.0/doc/commandline.rst000066400000000000000000000020321322741370200211040ustar00rootroot00000000000000The ``jsonpointer`` commandline utility ======================================= The JSON pointer package also installs a ``jsonpointer`` commandline utility that can be used to resolve a JSON pointers on JSON files. The program has the following usage :: usage: jsonpointer [-h] [--indent INDENT] [-v] POINTER FILE [FILE ...] Resolve a JSON pointer on JSON files positional arguments: POINTER File containing a JSON pointer expression FILE Files for which the pointer should be resolved optional arguments: -h, --help show this help message and exit --indent INDENT Indent output by n spaces -v, --version show program's version number and exit Example ^^^^^^^ .. code-block:: bash # inspect JSON files $ cat a.json { "a": [1, 2, 3] } $ cat b.json { "a": {"b": [1, 3, 4]}, "b": 1 } # inspect JSON pointer $ cat ptr.json "/a" # resolve JSON pointer $ jsonpointer ptr.json a.json b.json [1, 2, 3] {"b": [1, 3, 4]} python-json-pointer-2.0/doc/conf.py000066400000000000000000000174031322741370200173730ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # python-json-pointer documentation build configuration file, created by # sphinx-quickstart on Sat Apr 13 16:52:59 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.join(os.path.abspath('.'), '..')) import jsonpointer # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'python-json-pointer' copyright = jsonpointer.__author__ # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = jsonpointer.__version__ # The full version, including alpha/beta/rc tags. release = jsonpointer.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'python-json-pointerdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'python-json-pointer.tex', u'python-json-pointer Documentation', u'Stefan Kögl', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'python-json-pointer', u'python-json-pointer Documentation', [u'Stefan Kögl'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'python-json-pointer', u'python-json-pointer Documentation', u'Stefan Kögl', 'python-json-pointer', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' python-json-pointer-2.0/doc/index.rst000066400000000000000000000012341322741370200177300ustar00rootroot00000000000000.. python-json-pointer documentation master file, created by sphinx-quickstart on Sat Apr 13 16:52:59 2013. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. python-json-pointer =================== *python-json-pointer* is a Python library for resolving JSON pointers (`RFC 6901 `_). Python 2.7, 3.4+ and PyPy are supported. **Contents** .. toctree:: :maxdepth: 2 tutorial mod-jsonpointer commandline RFC 6901 Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` python-json-pointer-2.0/doc/mod-jsonpointer.rst000066400000000000000000000001671322741370200217540ustar00rootroot00000000000000.. mod-jsonpointer: The ``jsonpointer`` module ============================ .. automodule:: jsonpointer :members: python-json-pointer-2.0/doc/tutorial.rst000066400000000000000000000042211322741370200204630ustar00rootroot00000000000000Tutorial ======== Please refer to `RFC 6901 `_ for the exact pointer syntax. ``jsonpointer`` has two interfaces. The ``resolve_pointer`` method is basically a deep ``get``. .. code-block:: python >>> from jsonpointer import resolve_pointer >>> obj = {"foo": {"anArray": [ {"prop": 44}], "another prop": {"baz": "A string" }}} >>> resolve_pointer(obj, '') == obj True >>> resolve_pointer(obj, '/foo') == obj['foo'] True >>> resolve_pointer(obj, '/foo/another%20prop') == obj['foo']['another prop'] True >>> resolve_pointer(obj, '/foo/another%20prop/baz') == obj['foo']['another prop']['baz'] True >>> resolve_pointer(obj, '/foo/anArray/0') == obj['foo']['anArray'][0] True >>> resolve_pointer(obj, '/some/path', None) == None True The ``set_pointer`` method allows modifying a portion of an object using JSON pointer notation: .. code-block:: python >>> from jsonpointer import set_pointer >>> obj = {"foo": {"anArray": [ {"prop": 44}], "another prop": {"baz": "A string" }}} >>> set_pointer(obj, '/foo/anArray/0/prop', 55) {'foo': {'another prop': {'baz': 'A string'}, 'anArray': [{'prop': 55}]}} >>> obj {'foo': {'another prop': {'baz': 'A string'}, 'anArray': [{'prop': 55}]}} By default ``set_pointer`` modifies the original object. Pass ``inplace=False`` to create a copy and modify the copy instead: >>> from jsonpointer import set_pointer >>> obj = {"foo": {"anArray": [ {"prop": 44}], "another prop": {"baz": "A string" }}} >>> set_pointer(obj, '/foo/anArray/0/prop', 55, inplace=False) {'foo': {'another prop': {'baz': 'A string'}, 'anArray': [{'prop': 55}]}} >>> obj {'foo': {'another prop': {'baz': 'A string'}, 'anArray': [{'prop': 44}]}} The ``JsonPointer`` class wraps a (string) path and can be used to access the same path on several objects. .. code-block:: python >>> import jsonpointer >>> pointer = jsonpointer.JsonPointer('/foo/1') >>> obj1 = {'foo': ['a', 'b', 'c']} >>> pointer.resolve(obj1) 'b' >>> obj2 = {'foo': {'0': 1, '1': 10, '2': 100}} >>> pointer.resolve(obj2) 10 python-json-pointer-2.0/jsonpointer.py000066400000000000000000000231041322741370200202460ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # python-json-pointer - An implementation of the JSON Pointer syntax # https://github.com/stefankoegl/python-json-pointer # # Copyright (c) 2011 Stefan Kögl # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # """ Identify specific nodes in a JSON document (RFC 6901) """ from __future__ import unicode_literals # Will be parsed by setup.py to determine package metadata __author__ = 'Stefan Kögl ' __version__ = '2.0' __website__ = 'https://github.com/stefankoegl/python-json-pointer' __license__ = 'Modified BSD License' try: from itertools import izip str = unicode except ImportError: # Python 3 izip = zip try: from collections.abc import Mapping, Sequence except ImportError: # Python 3 from collections import Mapping, Sequence from itertools import tee import re import copy _nothing = object() def set_pointer(doc, pointer, value, inplace=True): """Resolves pointer against doc and sets the value of the target within doc. With inplace set to true, doc is modified as long as pointer is not the root. >>> obj = {'foo': {'anArray': [ {'prop': 44}], 'another prop': {'baz': 'A string' }}} >>> set_pointer(obj, '/foo/anArray/0/prop', 55) == \ {'foo': {'another prop': {'baz': 'A string'}, 'anArray': [{'prop': 55}]}} True >>> set_pointer(obj, '/foo/yet another prop', 'added prop') == \ {'foo': {'another prop': {'baz': 'A string'}, 'yet another prop': 'added prop', 'anArray': [{'prop': 55}]}} True >>> obj = {'foo': {}} >>> set_pointer(obj, '/foo/a%20b', 'x') == \ {'foo': {'a%20b': 'x' }} True """ pointer = JsonPointer(pointer) return pointer.set(doc, value, inplace) def resolve_pointer(doc, pointer, default=_nothing): """ Resolves pointer against doc and returns the referenced object >>> obj = {'foo': {'anArray': [ {'prop': 44}], 'another prop': {'baz': 'A string' }}, 'a%20b': 1, 'c d': 2} >>> resolve_pointer(obj, '') == obj True >>> resolve_pointer(obj, '/foo') == obj['foo'] True >>> resolve_pointer(obj, '/foo/another prop') == obj['foo']['another prop'] True >>> resolve_pointer(obj, '/foo/another prop/baz') == obj['foo']['another prop']['baz'] True >>> resolve_pointer(obj, '/foo/anArray/0') == obj['foo']['anArray'][0] True >>> resolve_pointer(obj, '/some/path', None) == None True >>> resolve_pointer(obj, '/a b', None) == None True >>> resolve_pointer(obj, '/a%20b') == 1 True >>> resolve_pointer(obj, '/c d') == 2 True >>> resolve_pointer(obj, '/c%20d', None) == None True """ pointer = JsonPointer(pointer) return pointer.resolve(doc, default) def pairwise(iterable): """ Transforms a list to a list of tuples of adjacent items s -> (s0,s1), (s1,s2), (s2, s3), ... >>> list(pairwise([])) [] >>> list(pairwise([1])) [] >>> list(pairwise([1, 2, 3, 4])) [(1, 2), (2, 3), (3, 4)] """ a, b = tee(iterable) for _ in b: break return izip(a, b) class JsonPointerException(Exception): pass class EndOfList(object): """Result of accessing element "-" of a list""" def __init__(self, list_): self.list_ = list_ def __repr__(self): return '{cls}({lst})'.format(cls=self.__class__.__name__, lst=repr(self.list_)) class JsonPointer(object): """A JSON Pointer that can reference parts of an JSON document""" # Array indices must not contain: # leading zeros, signs, spaces, decimals, etc _RE_ARRAY_INDEX = re.compile('0|[1-9][0-9]*$') _RE_INVALID_ESCAPE = re.compile('(~[^01]|~$)') def __init__(self, pointer): # validate escapes invalid_escape = self._RE_INVALID_ESCAPE.search(pointer) if invalid_escape: raise JsonPointerException('Found invalid escape {}'.format( invalid_escape.group())) parts = pointer.split('/') if parts.pop(0) != '': raise JsonPointerException('location must starts with /') parts = [unescape(part) for part in parts] self.parts = parts def to_last(self, doc): """Resolves ptr until the last step, returns (sub-doc, last-step)""" if not self.parts: return doc, None for part in self.parts[:-1]: doc = self.walk(doc, part) return doc, self.get_part(doc, self.parts[-1]) def resolve(self, doc, default=_nothing): """Resolves the pointer against doc and returns the referenced object""" for part in self.parts: try: doc = self.walk(doc, part) except JsonPointerException: if default is _nothing: raise else: return default return doc get = resolve def set(self, doc, value, inplace=True): """Resolve the pointer against the doc and replace the target with value.""" if len(self.parts) == 0: if inplace: raise JsonPointerException('cannot set root in place') return value if not inplace: doc = copy.deepcopy(doc) (parent, part) = self.to_last(doc) parent[part] = value return doc def get_part(self, doc, part): """Returns the next step in the correct type""" if isinstance(doc, Mapping): return part elif isinstance(doc, Sequence): if part == '-': return part if not self._RE_ARRAY_INDEX.match(str(part)): raise JsonPointerException("'%s' is not a valid sequence index" % part) return int(part) elif hasattr(doc, '__getitem__'): # Allow indexing via ducktyping # if the target has defined __getitem__ return part else: raise JsonPointerException("Document '%s' does not support indexing, " "must be mapping/sequence or support __getitem__" % type(doc)) def walk(self, doc, part): """ Walks one step in doc and returns the referenced part """ part = self.get_part(doc, part) assert hasattr(doc, '__getitem__'), "invalid document type %s" % (type(doc),) if isinstance(doc, Sequence): if part == '-': return EndOfList(doc) try: return doc[part] except IndexError: raise JsonPointerException("index '%s' is out of bounds" % (part, )) # Else the object is a mapping or supports __getitem__(so assume custom indexing) try: return doc[part] except KeyError: raise JsonPointerException("member '%s' not found in %s" % (part, doc)) def contains(self, ptr): """ Returns True if self contains the given ptr """ return self.parts[:len(ptr.parts)] == ptr.parts def __contains__(self, item): """ Returns True if self contains the given ptr """ return self.contains(item) @property def path(self): """Returns the string representation of the pointer >>> ptr = JsonPointer('/~0/0/~1').path == '/~0/0/~1' """ parts = [escape(part) for part in self.parts] return ''.join('/' + part for part in parts) def __eq__(self, other): """Compares a pointer to another object Pointers can be compared by comparing their strings (or splitted strings), because no two different parts can point to the same structure in an object (eg no different number representations) """ if not isinstance(other, JsonPointer): return False return self.parts == other.parts def __hash__(self): return hash(tuple(self.parts)) @classmethod def from_parts(cls, parts): """Constructs a JsonPointer from a list of (unescaped) paths >>> JsonPointer.from_parts(['a', '~', '/', 0]).path == '/a/~0/~1/0' True """ parts = [escape(str(part)) for part in parts] ptr = cls(''.join('/' + part for part in parts)) return ptr def escape(s): return s.replace('~', '~0').replace('/', '~1') def unescape(s): return s.replace('~1', '/').replace('~0', '~') python-json-pointer-2.0/makefile000066400000000000000000000004721322741370200170250ustar00rootroot00000000000000 help: @echo "jsonpointer" @echo "Makefile targets" @echo " - test: run tests" @echo " - coverage: run tests with coverage" @echo @echo "To install jsonpointer, type" @echo " python setup.py install" @echo test: python tests.py coverage: coverage run --source=jsonpointer tests.py coverage report -m python-json-pointer-2.0/requirements-dev.txt000066400000000000000000000000241322741370200213560ustar00rootroot00000000000000wheel pypandoc==1.4 python-json-pointer-2.0/setup.cfg000066400000000000000000000000341322741370200171400ustar00rootroot00000000000000[bdist_wheel] universal = 1 python-json-pointer-2.0/setup.py000066400000000000000000000037731322741370200170460ustar00rootroot00000000000000#!/usr/bin/env python from setuptools import setup import re import io import os.path dirname = os.path.dirname(os.path.abspath(__file__)) filename = os.path.join(dirname, 'jsonpointer.py') src = io.open(filename, encoding='utf-8').read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", src)) docstrings = re.findall('"""(.*)"""', src) PACKAGE = 'jsonpointer' MODULES = ( 'jsonpointer', ) AUTHOR_EMAIL = metadata['author'] VERSION = metadata['version'] WEBSITE = metadata['website'] LICENSE = metadata['license'] DESCRIPTION = docstrings[0] # Extract name and e-mail ("Firstname Lastname ") AUTHOR, EMAIL = re.match(r'(.*) <(.*)>', AUTHOR_EMAIL).groups() try: from pypandoc import convert read_md = lambda f: convert(f, 'rst') except ImportError: print('warning: pypandoc module not found, could not convert ' 'Markdown to RST') read_md = lambda f: open(f, 'r').read() CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities', ] setup(name=PACKAGE, version=VERSION, description=DESCRIPTION, long_description=read_md('README.md'), author=AUTHOR, author_email=EMAIL, license=LICENSE, url=WEBSITE, py_modules=MODULES, scripts=['bin/jsonpointer'], classifiers=CLASSIFIERS, python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', ) python-json-pointer-2.0/tests.py000077500000000000000000000230521322741370200170430ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import doctest import unittest import sys import copy from jsonpointer import resolve_pointer, EndOfList, JsonPointerException, \ JsonPointer, set_pointer class SpecificationTests(unittest.TestCase): """ Tests all examples from the JSON Pointer specification """ def test_example(self): doc = { "foo": ["bar", "baz"], "": 0, "a/b": 1, "c%d": 2, "e^f": 3, "g|h": 4, "i\\j": 5, "k\"l": 6, " ": 7, "m~n": 8 } self.assertEqual(resolve_pointer(doc, ""), doc) self.assertEqual(resolve_pointer(doc, "/foo"), ["bar", "baz"]) self.assertEqual(resolve_pointer(doc, "/foo/0"), "bar") self.assertEqual(resolve_pointer(doc, "/"), 0) self.assertEqual(resolve_pointer(doc, "/a~1b"), 1) self.assertEqual(resolve_pointer(doc, "/c%d"), 2) self.assertEqual(resolve_pointer(doc, "/e^f"), 3) self.assertEqual(resolve_pointer(doc, "/g|h"), 4) self.assertEqual(resolve_pointer(doc, "/i\\j"), 5) self.assertEqual(resolve_pointer(doc, "/k\"l"), 6) self.assertEqual(resolve_pointer(doc, "/ "), 7) self.assertEqual(resolve_pointer(doc, "/m~0n"), 8) def test_eol(self): doc = { "foo": ["bar", "baz"] } self.assertTrue(isinstance(resolve_pointer(doc, "/foo/-"), EndOfList)) self.assertRaises(JsonPointerException, resolve_pointer, doc, "/foo/-/1") def test_round_trip(self): paths = [ "", "/foo", "/foo/0", "/", "/a~1b", "/c%d", "/e^f", "/g|h", "/i\\j", "/k\"l", "/ ", "/m~0n", '/\xee', ] for path in paths: ptr = JsonPointer(path) self.assertEqual(path, ptr.path) parts = ptr.parts new_ptr = JsonPointer.from_parts(parts) self.assertEqual(ptr, new_ptr) class ComparisonTests(unittest.TestCase): def setUp(self): self.ptr1 = JsonPointer("/a/b/c") self.ptr2 = JsonPointer("/a/b") self.ptr3 = JsonPointer("/b/c") def test_eq_hash(self): p1 = JsonPointer("/something/1/b") p2 = JsonPointer("/something/1/b") p3 = JsonPointer("/something/1.0/b") self.assertEqual(p1, p2) self.assertNotEqual(p1, p3) self.assertNotEqual(p2, p3) self.assertEqual(hash(p1), hash(p2)) self.assertNotEqual(hash(p1), hash(p3)) self.assertNotEqual(hash(p2), hash(p3)) # a pointer compares not-equal to objects of other types self.assertFalse(p1 == "/something/1/b") def test_contains(self): self.assertTrue(self.ptr1.contains(self.ptr2)) self.assertTrue(self.ptr1.contains(self.ptr1)) self.assertFalse(self.ptr1.contains(self.ptr3)) def test_contains_magic(self): self.assertTrue(self.ptr2 in self.ptr1) self.assertTrue(self.ptr1 in self.ptr1) self.assertFalse(self.ptr3 in self.ptr1) class WrongInputTests(unittest.TestCase): def test_no_start_slash(self): # an exception is raised when the pointer string does not start with / self.assertRaises(JsonPointerException, JsonPointer, 'some/thing') def test_invalid_index(self): # 'a' is not a valid list index doc = [0, 1, 2] self.assertRaises(JsonPointerException, resolve_pointer, doc, '/a') def test_oob(self): # this list does not have 10 members doc = [0, 1, 2] self.assertRaises(JsonPointerException, resolve_pointer, doc, '/10') def test_trailing_escape(self): self.assertRaises(JsonPointerException, JsonPointer, '/foo/bar~') def test_invalid_escape(self): self.assertRaises(JsonPointerException, JsonPointer, '/foo/bar~2') class ToLastTests(unittest.TestCase): def test_empty_path(self): doc = {'a': [1, 2, 3]} ptr = JsonPointer('') last, nxt = ptr.to_last(doc) self.assertEqual(doc, last) self.assertTrue(nxt is None) def test_path(self): doc = {'a': [{'b': 1, 'c': 2}, 5]} ptr = JsonPointer('/a/0/b') last, nxt = ptr.to_last(doc) self.assertEqual(last, {'b': 1, 'c': 2}) self.assertEqual(nxt, 'b') class SetTests(unittest.TestCase): def test_set(self): doc = { "foo": ["bar", "baz"], "": 0, "a/b": 1, "c%d": 2, "e^f": 3, "g|h": 4, "i\\j": 5, "k\"l": 6, " ": 7, "m~n": 8 } origdoc = copy.deepcopy(doc) # inplace=False newdoc = set_pointer(doc, "/foo/1", "cod", inplace=False) self.assertEqual(resolve_pointer(newdoc, "/foo/1"), "cod") newdoc = set_pointer(doc, "/", 9, inplace=False) self.assertEqual(resolve_pointer(newdoc, "/"), 9) newdoc = set_pointer(doc, "/fud", {}, inplace=False) newdoc = set_pointer(newdoc, "/fud/gaw", [1, 2, 3], inplace=False) self.assertEqual(resolve_pointer(newdoc, "/fud"), {'gaw' : [1, 2, 3]}) newdoc = set_pointer(doc, "", 9, inplace=False) self.assertEqual(newdoc, 9) self.assertEqual(doc, origdoc) # inplace=True set_pointer(doc, "/foo/1", "cod") self.assertEqual(resolve_pointer(doc, "/foo/1"), "cod") set_pointer(doc, "/", 9) self.assertEqual(resolve_pointer(doc, "/"), 9) self.assertRaises(JsonPointerException, set_pointer, doc, "/fud/gaw", 9) set_pointer(doc, "/fud", {}) set_pointer(doc, "/fud/gaw", [1, 2, 3] ) self.assertEqual(resolve_pointer(doc, "/fud"), {'gaw' : [1, 2, 3]}) self.assertRaises(JsonPointerException, set_pointer, doc, "", 9) class AltTypesTests(unittest.TestCase): class Node(object): def __init__(self, name, parent=None): self.name = name self.parent = parent self.left = None self.right = None def set_left(self, node): node.parent = self self.left = node def set_right(self, node): node.parent = self self.right = node def __getitem__(self, key): if key == 'left': return self.left if key == 'right': return self.right raise KeyError("Only left and right supported") def __setitem__(self, key, val): if key == 'left': return self.set_left(val) if key == 'right': return self.set_right(val) raise KeyError("Only left and right supported: %s" % key) class mdict(object): def __init__(self, d): self._d = d def __getitem__(self, item): return self._d[item] mdict = mdict({'root': {'1': {'2': '3'}}}) Node = Node def test_alttypes(self): Node = self.Node root = Node('root') root.set_left(Node('a')) root.left.set_left(Node('aa')) root.left.set_right(Node('ab')) root.set_right(Node('b')) root.right.set_left(Node('ba')) root.right.set_right(Node('bb')) self.assertEqual(resolve_pointer(root, '/left').name, 'a') self.assertEqual(resolve_pointer(root, '/left/right').name, 'ab') self.assertEqual(resolve_pointer(root, '/right').name, 'b') self.assertEqual(resolve_pointer(root, '/right/left').name, 'ba') newroot = set_pointer(root, '/left/right', Node('AB'), inplace=False) self.assertEqual(resolve_pointer(root, '/left/right').name, 'ab') self.assertEqual(resolve_pointer(newroot, '/left/right').name, 'AB') set_pointer(root, '/left/right', Node('AB')) self.assertEqual(resolve_pointer(root, '/left/right').name, 'AB') def test_mock_dict_sanity(self): doc = self.mdict default = None # TODO: Generate this automatically for any given object path_to_expected_value = { '/root/1': {'2': '3'}, '/root': {'1': {'2': '3'}}, '/root/1/2': '3', } for path, expected_value in iter(path_to_expected_value.items()): self.assertEqual(resolve_pointer(doc, path, default), expected_value) def test_mock_dict_returns_default(self): doc = self.mdict default = None path_to_expected_value = { '/foo': default, '/x/y/z/d': default } for path, expected_value in iter(path_to_expected_value.items()): self.assertEqual(resolve_pointer(doc, path, default), expected_value) def test_mock_dict_raises_key_error(self): doc = self.mdict self.assertRaises(JsonPointerException, resolve_pointer, doc, '/foo') self.assertRaises(JsonPointerException, resolve_pointer, doc, '/root/1/2/3/4') suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(SpecificationTests)) suite.addTest(unittest.makeSuite(ComparisonTests)) suite.addTest(unittest.makeSuite(WrongInputTests)) suite.addTest(unittest.makeSuite(ToLastTests)) suite.addTest(unittest.makeSuite(SetTests)) suite.addTest(unittest.makeSuite(AltTypesTests)) modules = ['jsonpointer'] for module in modules: m = __import__(module, fromlist=[module]) suite.addTest(doctest.DocTestSuite(m)) runner = unittest.TextTestRunner(verbosity=1) result = runner.run(suite) if not result.wasSuccessful(): sys.exit(1)