jsonpointer 3.6__tar.gz → 3.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,3 +2,5 @@ include AUTHORS
2
2
  include LICENSE.txt
3
3
  include README.md
4
4
  include tests.py
5
+ include doc/*.rst
6
+ recursive-include jsonpointer-stubs *.pyi
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jsonpointer
3
- Version: 3.6
3
+ Version: 3.8
4
4
  Summary: Identify specific nodes in a JSON document (RFC 6901)
5
5
  Home-page: https://github.com/stefankoegl/python-json-pointer
6
6
  Author: Stefan Kögl
@@ -22,6 +22,7 @@ Classifier: Programming Language :: Python :: Implementation :: CPython
22
22
  Classifier: Programming Language :: Python :: Implementation :: PyPy
23
23
  Classifier: Topic :: Software Development :: Libraries
24
24
  Classifier: Topic :: Utilities
25
+ Classifier: Typing :: Typed
25
26
  Requires-Python: >=3.10
26
27
  Description-Content-Type: text/markdown
27
28
  License-File: LICENSE.txt
@@ -60,6 +60,8 @@ def parse_pointer(args):
60
60
  # 2026-10-11: Trim file line endings without changing member names.
61
61
  try:
62
62
  ptr = args.pointer_file.read().rstrip("\r\n")
63
+ except UnicodeDecodeError as e:
64
+ parser.error('could not decode pointer file: %s' % e)
63
65
  finally:
64
66
  if args.pointer_file is not sys.stdin:
65
67
  args.pointer_file.close()
@@ -0,0 +1,76 @@
1
+ The ``jsonpointer`` commandline utility
2
+ =======================================
3
+
4
+ The JSON pointer package also installs a ``jsonpointer`` commandline utility
5
+ that can be used to resolve a JSON pointers on JSON files.
6
+
7
+ The program has the following usage ::
8
+
9
+ usage: jsonpointer [-h] [-f POINTER_FILE | -p POINTER] [--indent INDENT]
10
+ [--continue-on-error] [-v]
11
+ [POINTER] FILE [FILE ...]
12
+
13
+ Resolve a JSON pointer on JSON files
14
+
15
+ positional arguments:
16
+ POINTER A JSON pointer expression (if neither -f nor -p is
17
+ given)
18
+ FILE Files for which the pointer should be resolved
19
+
20
+ options:
21
+ -h, --help show this help message and exit
22
+ -f POINTER_FILE, --pointer-file POINTER_FILE
23
+ File containing a JSON pointer expression
24
+ -p POINTER, --pointer POINTER
25
+ A JSON pointer expression
26
+ --indent INDENT Indent output by n spaces
27
+ --continue-on-error Continue with remaining files after JSON or text
28
+ decoding errors
29
+ -v, --version show program's version number and exit
30
+
31
+ The pointer can be passed as the first positional argument, with ``-p``, or
32
+ read from a file with ``-f``.
33
+
34
+ JSON input files and pointer files are read as UTF-8.
35
+
36
+ The exit status is 0 if the pointer could be resolved on all files, 1 if it
37
+ could not be resolved on at least one file (the remaining files are still
38
+ processed) and 2 on usage errors, such as an invalid pointer or a missing
39
+ file.
40
+
41
+ By default, invalid JSON or a text decoding error stops processing. With
42
+ ``--continue-on-error``, these errors are reported on standard error with
43
+ the file name and decoder details, and the remaining files are processed.
44
+ The exit status is 1 if any file has such an error, even if later files
45
+ succeed. Missing files and other usage errors still stop processing with
46
+ status 2.
47
+
48
+ Example
49
+ ^^^^^^^
50
+
51
+ .. code-block:: bash
52
+
53
+ # inspect JSON files
54
+ $ cat a.json
55
+ { "a": [1, 2, 3] }
56
+
57
+ $ cat b.json
58
+ { "a": {"b": [1, 3, 4]}, "b": 1 }
59
+
60
+ # resolve JSON pointer
61
+ $ jsonpointer /a a.json b.json
62
+ [1, 2, 3]
63
+ {"b": [1, 3, 4]}
64
+
65
+ # same, using the -p option
66
+ $ jsonpointer -p /a a.json b.json
67
+ [1, 2, 3]
68
+ {"b": [1, 3, 4]}
69
+
70
+ # same, reading the pointer from a file
71
+ $ cat ptr.txt
72
+ /a
73
+
74
+ $ jsonpointer -f ptr.txt a.json b.json
75
+ [1, 2, 3]
76
+ {"b": [1, 3, 4]}
@@ -0,0 +1,30 @@
1
+ .. python-json-pointer documentation master file, created by
2
+ sphinx-quickstart on Sat Apr 13 16:52:59 2013.
3
+ You can adapt this file completely to your liking, but it should at least
4
+ contain the root `toctree` directive.
5
+
6
+ python-json-pointer
7
+ ===================
8
+
9
+ *python-json-pointer* is a Python library for resolving JSON pointers (`RFC
10
+ 6901 <http://tools.ietf.org/html/rfc6901>`_). Python 3.10+
11
+ and PyPy are supported.
12
+
13
+ **Contents**
14
+
15
+ .. toctree::
16
+ :maxdepth: 2
17
+
18
+ tutorial
19
+ mod-jsonpointer
20
+ commandline
21
+ RFC 6901 <http://tools.ietf.org/html/rfc6901>
22
+
23
+
24
+ Indices and tables
25
+ ==================
26
+
27
+ * :ref:`genindex`
28
+ * :ref:`modindex`
29
+ * :ref:`search`
30
+
@@ -0,0 +1,7 @@
1
+ .. mod-jsonpointer:
2
+
3
+ The ``jsonpointer`` module
4
+ ============================
5
+
6
+ .. automodule:: jsonpointer
7
+ :members:
@@ -0,0 +1,107 @@
1
+ Tutorial
2
+ ========
3
+
4
+ Please refer to `RFC 6901 <http://tools.ietf.org/html/rfc6901>`_ for the exact
5
+ pointer syntax. ``jsonpointer`` has two interfaces. The ``resolve_pointer``
6
+ method is basically a deep ``get``.
7
+
8
+ .. code-block:: python
9
+
10
+ >>> from jsonpointer import resolve_pointer
11
+ >>> obj = {"foo": {"anArray": [ {"prop": 44}], "another prop": {"baz": "A string" }}}
12
+
13
+ >>> resolve_pointer(obj, '') == obj
14
+ True
15
+
16
+ >>> resolve_pointer(obj, '/foo') == obj['foo']
17
+ True
18
+
19
+ >>> resolve_pointer(obj, '/foo/another prop') == obj['foo']['another prop']
20
+ True
21
+
22
+ >>> resolve_pointer(obj, '/foo/another prop/baz') == obj['foo']['another prop']['baz']
23
+ True
24
+
25
+ >>> resolve_pointer(obj, '/foo/anArray/0') == obj['foo']['anArray'][0]
26
+ True
27
+
28
+ >>> resolve_pointer(obj, '/some/path', None) == None
29
+ True
30
+
31
+
32
+ The ``set_pointer`` method allows modifying a portion of an object using
33
+ JSON pointer notation:
34
+
35
+ .. code-block:: python
36
+
37
+ >>> from jsonpointer import set_pointer
38
+ >>> obj = {"foo": {"anArray": [ {"prop": 44}], "another prop": {"baz": "A string" }}}
39
+
40
+ >>> set_pointer(obj, '/foo/anArray/0/prop', 55)
41
+ {'foo': {'anArray': [{'prop': 55}], 'another prop': {'baz': 'A string'}}}
42
+
43
+ >>> obj
44
+ {'foo': {'anArray': [{'prop': 55}], 'another prop': {'baz': 'A string'}}}
45
+
46
+ By default ``set_pointer`` modifies the original object. Pass ``inplace=False``
47
+ to create a copy and modify the copy instead:
48
+
49
+ >>> from jsonpointer import set_pointer
50
+ >>> obj = {"foo": {"anArray": [ {"prop": 44}], "another prop": {"baz": "A string" }}}
51
+
52
+ >>> set_pointer(obj, '/foo/anArray/0/prop', 55, inplace=False)
53
+ {'foo': {'anArray': [{'prop': 55}], 'another prop': {'baz': 'A string'}}}
54
+
55
+ >>> obj
56
+ {'foo': {'anArray': [{'prop': 44}], 'another prop': {'baz': 'A string'}}}
57
+
58
+ By default, setting a value below a member that does not exist raises a
59
+ ``JsonPointerException``. Pass ``create=True`` to create missing members as
60
+ dicts instead. Missing list elements can be created by referencing the end of
61
+ the list, either with ``-`` or with an index equal to the length of the list:
62
+
63
+ >>> from jsonpointer import set_pointer
64
+ >>> obj = {}
65
+
66
+ >>> set_pointer(obj, '/cat/name', 'whiskers', create=True)
67
+ {'cat': {'name': 'whiskers'}}
68
+
69
+ >>> obj = {'cats': []}
70
+
71
+ >>> set_pointer(obj, '/cats/-/name', 'whiskers', create=True)
72
+ {'cats': [{'name': 'whiskers'}]}
73
+
74
+ The ``JsonPointer`` class wraps a (string) path and can be used to access the
75
+ same path on several objects.
76
+
77
+ .. code-block:: python
78
+
79
+ >>> import jsonpointer
80
+
81
+ >>> pointer = jsonpointer.JsonPointer('/foo/1')
82
+
83
+ >>> obj1 = {'foo': ['a', 'b', 'c']}
84
+ >>> pointer.resolve(obj1)
85
+ 'b'
86
+
87
+ >>> obj2 = {'foo': {'0': 1, '1': 10, '2': 100}}
88
+ >>> pointer.resolve(obj2)
89
+ 10
90
+
91
+ Checking pointer prefixes
92
+ -------------------------
93
+
94
+ ``child.contains(parent)`` checks whether the parent's parts are a prefix of
95
+ the child's parts. The equivalent membership expression is ``parent in child``.
96
+ The comparison is between whole path parts, so ``/foo/b`` is not a prefix of
97
+ ``/foo/bar``. Equal pointers and the root pointer are prefixes too:
98
+
99
+ >>> from jsonpointer import JsonPointer
100
+ >>> parent = JsonPointer('/foo')
101
+ >>> child = JsonPointer('/foo/bar')
102
+ >>> child.contains(parent)
103
+ True
104
+ >>> parent in child
105
+ True
106
+ >>> child in parent
107
+ False
@@ -0,0 +1,63 @@
1
+ from collections.abc import Iterable, Iterator
2
+ from re import Pattern
3
+ from typing import Any, Final, TypeVar
4
+
5
+ from typing_extensions import Self
6
+
7
+ _T = TypeVar("_T")
8
+
9
+ __author__: Final[str]
10
+ __version__: Final[str]
11
+ __website__: Final[str]
12
+ __license__: Final[str]
13
+
14
+ VERBOSE_EXCEPTIONS: bool
15
+
16
+ def set_pointer(
17
+ doc: Any,
18
+ pointer: str,
19
+ value: Any,
20
+ inplace: bool = True,
21
+ create: bool = False,
22
+ ) -> Any: ...
23
+ def resolve_pointer(doc: Any, pointer: str, default: Any = ...) -> Any: ...
24
+ def pairwise(iterable: Iterable[_T]) -> Iterator[tuple[_T, _T]]: ...
25
+
26
+ class JsonPointerException(Exception): ...
27
+
28
+ class EndOfList:
29
+ list_: Any
30
+ def __init__(self, list_: Any) -> None: ...
31
+
32
+ class JsonPointer:
33
+ _RE_ARRAY_INDEX: Pattern[str]
34
+ _RE_INVALID_ESCAPE: Pattern[str]
35
+ parts: list[str]
36
+ def __init__(self, pointer: str) -> None: ...
37
+ def to_last(self, doc: Any) -> tuple[Any, str | int | None]: ...
38
+ def resolve(self, doc: Any, default: Any = ...) -> Any: ...
39
+ def get(self, doc: Any, default: Any = ...) -> Any: ...
40
+ def set(
41
+ self,
42
+ doc: Any,
43
+ value: Any,
44
+ inplace: bool = True,
45
+ create: bool = False,
46
+ ) -> Any: ...
47
+ @classmethod
48
+ def get_part(cls, doc: Any, part: str | int) -> str | int: ...
49
+ def get_parts(self) -> list[str]: ...
50
+ def walk(self, doc: Any, part: str | int) -> Any: ...
51
+ def contains(self, ptr: JsonPointer) -> bool: ...
52
+ def __contains__(self, item: JsonPointer) -> bool: ...
53
+ def join(self, suffix: JsonPointer | str | Iterable[object]) -> Self: ...
54
+ def __truediv__(self, suffix: JsonPointer | str | Iterable[object]) -> Self: ...
55
+ @property
56
+ def path(self) -> str: ...
57
+ def __eq__(self, other: object) -> bool: ...
58
+ def __hash__(self) -> int: ...
59
+ @classmethod
60
+ def from_parts(cls, parts: Iterable[object]) -> Self: ...
61
+
62
+ def escape(s: str) -> str: ...
63
+ def unescape(s: str) -> str: ...
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jsonpointer
3
- Version: 3.6
3
+ Version: 3.8
4
4
  Summary: Identify specific nodes in a JSON document (RFC 6901)
5
5
  Home-page: https://github.com/stefankoegl/python-json-pointer
6
6
  Author: Stefan Kögl
@@ -22,6 +22,7 @@ Classifier: Programming Language :: Python :: Implementation :: CPython
22
22
  Classifier: Programming Language :: Python :: Implementation :: PyPy
23
23
  Classifier: Topic :: Software Development :: Libraries
24
24
  Classifier: Topic :: Utilities
25
+ Classifier: Typing :: Typed
25
26
  Requires-Python: >=3.10
26
27
  Description-Content-Type: text/markdown
27
28
  License-File: LICENSE.txt
@@ -7,6 +7,11 @@ setup.cfg
7
7
  setup.py
8
8
  tests.py
9
9
  bin/jsonpointer
10
+ doc/commandline.rst
11
+ doc/index.rst
12
+ doc/mod-jsonpointer.rst
13
+ doc/tutorial.rst
14
+ jsonpointer-stubs/__init__.pyi
10
15
  jsonpointer.egg-info/PKG-INFO
11
16
  jsonpointer.egg-info/SOURCES.txt
12
17
  jsonpointer.egg-info/dependency_links.txt
@@ -0,0 +1,2 @@
1
+ jsonpointer
2
+ jsonpointer-stubs
@@ -32,7 +32,7 @@
32
32
 
33
33
  # Will be parsed by setup.py to determine package metadata
34
34
  __author__ = 'Stefan Kögl <stefan@skoegl.net>'
35
- __version__ = '3.6'
35
+ __version__ = '3.8'
36
36
  __website__ = 'https://github.com/stefankoegl/python-json-pointer'
37
37
  __license__ = 'Modified BSD License'
38
38
 
@@ -1,5 +1,6 @@
1
1
  [flake8]
2
2
  max-line-length = 120
3
+ filename = *.py,./bin/jsonpointer
3
4
  exclude = .git,.tox,dist,doc,*egg,build,.venv
4
5
 
5
6
  [egg_info]
@@ -47,6 +47,7 @@ CLASSIFIERS = [
47
47
  'Programming Language :: Python :: Implementation :: PyPy',
48
48
  'Topic :: Software Development :: Libraries',
49
49
  'Topic :: Utilities',
50
+ 'Typing :: Typed',
50
51
  ]
51
52
 
52
53
  setup(
@@ -60,6 +61,9 @@ setup(
60
61
  license=LICENSE,
61
62
  url=WEBSITE,
62
63
  py_modules=MODULES,
64
+ # PEP 561 stub-only package, shipped in the same distribution
65
+ packages=['jsonpointer-stubs'],
66
+ package_data={'jsonpointer-stubs': ['__init__.pyi']},
63
67
  scripts=['bin/jsonpointer'],
64
68
  classifiers=CLASSIFIERS,
65
69
  python_requires='>=3.10',
@@ -6,9 +6,11 @@ import io
6
6
  import json
7
7
  import os
8
8
  import runpy
9
+ import shlex
9
10
  import subprocess
10
11
  import sys
11
12
  import tempfile
13
+ import textwrap
12
14
  import unittest
13
15
  from contextlib import redirect_stderr, redirect_stdout
14
16
  from unittest import mock
@@ -622,6 +624,30 @@ class CommandLineTests(unittest.TestCase):
622
624
  os.path.join(self.dir, 'a.json'))
623
625
  self.assertEqual(caught.exception.code, 2)
624
626
 
627
+ def test_closes_pointer_file_after_decoding_error(self):
628
+ path = os.path.join(self.dir, 'invalid-pointer.txt')
629
+ with open(path, 'wb') as f:
630
+ f.write(b'/\xff')
631
+ with self.assertRaises(SystemExit) as caught:
632
+ self._run_with_retained_files(
633
+ '-f', path, os.path.join(self.dir, 'a.json'))
634
+ self.assertEqual(caught.exception.code, 2)
635
+
636
+ def test_pointer_decoding_error_keeps_stdin_open(self):
637
+ cli = runpy.run_path(self.SCRIPT)
638
+ stdin = io.TextIOWrapper(io.BytesIO(b'/\xff'), encoding='utf-8')
639
+ self.addCleanup(stdin.close)
640
+ args = [self.SCRIPT, '-f', '-', os.path.join(self.dir, 'a.json')]
641
+ with mock.patch.object(sys, 'argv', args), \
642
+ mock.patch.object(sys, 'stdin', stdin), \
643
+ mock.patch('builtins.open') as open_file, \
644
+ redirect_stderr(io.StringIO()):
645
+ with self.assertRaises(SystemExit) as caught:
646
+ cli['resolve_files']()
647
+ self.assertEqual(caught.exception.code, 2)
648
+ open_file.assert_not_called()
649
+ self.assertFalse(stdin.closed)
650
+
625
651
  def test_closes_inputs_after_json_errors(self):
626
652
  self._write('invalid.json', '{"a": }')
627
653
  with self.assertRaises(json.JSONDecodeError):
@@ -711,6 +737,19 @@ class CommandLineTests(unittest.TestCase):
711
737
  self.assertEqual(proc.returncode, 2)
712
738
  self.assertIn("invalid JSON pointer 'a'", proc.stderr)
713
739
 
740
+ def test_invalid_pointer_file_encoding(self):
741
+ with open(os.path.join(self.dir, 'bad.txt'), 'wb') as f:
742
+ f.write(b'/\xff')
743
+ for options in ([], ['--continue-on-error']):
744
+ with self.subTest(options=options):
745
+ proc = self._run(*options, '-f', 'bad.txt',
746
+ 'a.json', 'b.json')
747
+ self.assertEqual(proc.returncode, 2, proc.stderr)
748
+ self.assertEqual(proc.stdout, '')
749
+ self.assertIn('could not decode pointer file:', proc.stderr)
750
+ self.assertIn('decode', proc.stderr)
751
+ self.assertNotIn('Traceback', proc.stderr)
752
+
714
753
  def test_empty_pointer(self):
715
754
  proc = self._run('', 'a.json')
716
755
  self.assertEqual(proc.returncode, 0, proc.stderr)
@@ -886,6 +925,67 @@ class VerboseExceptionsTests(unittest.TestCase):
886
925
  self.assertIn('bar', str(e))
887
926
 
888
927
 
928
+ class DocExampleTests(unittest.TestCase):
929
+ """ Runs the shell examples from the documentation """
930
+
931
+ ROOT = os.path.dirname(os.path.abspath(__file__))
932
+ SCRIPT = os.path.join(ROOT, 'bin', 'jsonpointer')
933
+
934
+ def _examples(self, name):
935
+ """ Yields (command, expected output) pairs of the shell sessions in
936
+ the ``code-block:: bash`` directives of the given doc file """
937
+ with open(os.path.join(self.ROOT, 'doc', name), encoding='utf-8') as f:
938
+ blocks = f.read().split('.. code-block:: bash\n')[1:]
939
+ self.assertTrue(blocks, 'no bash examples found in ' + name)
940
+
941
+ for block in blocks:
942
+ # The block ends at the first non-indented line
943
+ lines = []
944
+ for line in block.splitlines()[1:]:
945
+ if line and not line[0].isspace():
946
+ break
947
+ lines.append(line)
948
+ lines = textwrap.dedent('\n'.join(lines)).splitlines()
949
+
950
+ cmd, output = None, []
951
+ for line in lines + ['']:
952
+ is_output = line.strip() and not line.startswith(('$ ', '#'))
953
+ if cmd is not None and is_output:
954
+ output.append(line)
955
+ continue
956
+ if cmd is not None:
957
+ yield cmd, ''.join(out + '\n' for out in output)
958
+ cmd, output = None, []
959
+ if line.startswith('$ '):
960
+ cmd = line[2:]
961
+
962
+ def test_commandline_examples(self):
963
+ tmpdir = tempfile.TemporaryDirectory()
964
+ self.addCleanup(tmpdir.cleanup)
965
+ env = dict(os.environ, PYTHONPATH=self.ROOT, PYTHONUTF8='1')
966
+
967
+ examples = list(self._examples('commandline.rst'))
968
+ self.assertTrue(any(cmd.startswith('jsonpointer ')
969
+ for cmd, _ in examples))
970
+ for cmd, expected in examples:
971
+ with self.subTest(cmd=cmd):
972
+ args = shlex.split(cmd)
973
+ if args[0] == 'cat':
974
+ # "cat" shows the input files used by later examples
975
+ path = os.path.join(tmpdir.name, args[1])
976
+ with open(path, 'w', encoding='utf-8') as f:
977
+ f.write(expected)
978
+ continue
979
+
980
+ self.assertEqual(args[0], 'jsonpointer')
981
+ result = subprocess.run([sys.executable, self.SCRIPT] + args[1:],
982
+ cwd=tmpdir.name, env=env,
983
+ capture_output=True, encoding='utf-8')
984
+ self.assertEqual(result.returncode, 0, result.stderr)
985
+ self.assertEqual(result.stdout, expected)
986
+
987
+
889
988
  def load_tests(loader, tests, ignore):
890
989
  tests.addTests(doctest.DocTestSuite(jsonpointer))
990
+ tests.addTests(doctest.DocFileSuite('doc/tutorial.rst'))
891
991
  return tests
@@ -1 +0,0 @@
1
- jsonpointer
File without changes
File without changes
File without changes