jsonpointer 3.7__tar.gz → 3.9__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.7
3
+ Version: 3.9
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
@@ -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.7
3
+ Version: 3.9
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.7'
35
+ __version__ = '3.9'
36
36
  __website__ = 'https://github.com/stefankoegl/python-json-pointer'
37
37
  __license__ = 'Modified BSD License'
38
38
 
@@ -275,8 +275,9 @@ class JsonPointer:
275
275
  elif isinstance(parent, Sequence) and part == '-':
276
276
  try:
277
277
  parent.append(value)
278
- except AttributeError as e:
279
- # immutable sequences, such as tuples, can't be appended to
278
+ except (AttributeError, TypeError) as e:
279
+ # Immutable sequences can't be appended to; typed sequences
280
+ # can reject the value just like an indexed assignment.
280
281
  raise JsonPointerException("Invalid assignment target: %s" % (e,))
281
282
  else:
282
283
  try:
@@ -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
@@ -81,6 +83,17 @@ class SpecificationTests(unittest.TestCase):
81
83
  new_ptr = JsonPointer.from_parts(parts)
82
84
  self.assertEqual(ptr, new_ptr)
83
85
 
86
+ def test_escaped_tilde_is_not_decoded_twice(self):
87
+ # RFC 6901 section 4: decode ~1 before ~0, so ~01 becomes ~1, not /.
88
+ pointer = JsonPointer('/~01')
89
+ self.assertEqual(pointer.parts, ['~1'])
90
+ self.assertEqual(JsonPointer.from_parts(pointer.parts).path, '/~01')
91
+
92
+ doc = {'~1': 'tilde member', '/': 'slash member'}
93
+ self.assertEqual(resolve_pointer(doc, '/~01'), 'tilde member')
94
+ set_pointer(doc, '/~01', 'updated')
95
+ self.assertEqual(doc, {'~1': 'updated', '/': 'slash member'})
96
+
84
97
  def test_str_and_repr(self):
85
98
  paths = [
86
99
  ("", "", "JsonPointer('')"),
@@ -454,6 +467,34 @@ class SetTests(unittest.TestCase):
454
467
  "/cat/name", "whiskers")
455
468
  self.assertEqual(doc, {})
456
469
 
470
+ def test_set_sequence_append_invalid_type(self):
471
+ for pointer, create in (("/items/0", False), ("/items/-", False),
472
+ ("/items/-", True), ("/items/1", True)):
473
+ for inplace in (False, True):
474
+ with self.subTest(pointer=pointer, create=create, inplace=inplace):
475
+ doc = {"items": bytearray([1])}
476
+ with self.assertRaisesRegex(JsonPointerException, "Invalid assignment target:"):
477
+ set_pointer(doc, pointer, "invalid", inplace=inplace, create=create)
478
+ self.assertEqual(doc, {"items": bytearray([1])})
479
+
480
+ def test_set_create_sequence_append_invalid_child(self):
481
+ for pointer in ("/items/-/leaf", "/items/1/leaf"):
482
+ with self.subTest(pointer=pointer):
483
+ doc = {"items": bytearray([1])}
484
+ with self.assertRaisesRegex(JsonPointerException, "Invalid assignment target:"):
485
+ set_pointer(doc, pointer, 7, create=True)
486
+ self.assertEqual(doc, {"items": bytearray([1])})
487
+
488
+ def test_set_sequence_append_valid_type(self):
489
+ for pointer, create in (("/items/-", False), ("/items/-", True),
490
+ ("/items/1", True)):
491
+ for inplace in (False, True):
492
+ with self.subTest(pointer=pointer, create=create, inplace=inplace):
493
+ doc = {"items": bytearray([1])}
494
+ result = set_pointer(doc, pointer, 2, inplace=inplace, create=create)
495
+ self.assertEqual(result, {"items": bytearray([1, 2])})
496
+ self.assertEqual(doc, result if inplace else {"items": bytearray([1])})
497
+
457
498
 
458
499
  class AltTypesTests(unittest.TestCase):
459
500
  class Node(object):
@@ -923,6 +964,67 @@ class VerboseExceptionsTests(unittest.TestCase):
923
964
  self.assertIn('bar', str(e))
924
965
 
925
966
 
967
+ class DocExampleTests(unittest.TestCase):
968
+ """ Runs the shell examples from the documentation """
969
+
970
+ ROOT = os.path.dirname(os.path.abspath(__file__))
971
+ SCRIPT = os.path.join(ROOT, 'bin', 'jsonpointer')
972
+
973
+ def _examples(self, name):
974
+ """ Yields (command, expected output) pairs of the shell sessions in
975
+ the ``code-block:: bash`` directives of the given doc file """
976
+ with open(os.path.join(self.ROOT, 'doc', name), encoding='utf-8') as f:
977
+ blocks = f.read().split('.. code-block:: bash\n')[1:]
978
+ self.assertTrue(blocks, 'no bash examples found in ' + name)
979
+
980
+ for block in blocks:
981
+ # The block ends at the first non-indented line
982
+ lines = []
983
+ for line in block.splitlines()[1:]:
984
+ if line and not line[0].isspace():
985
+ break
986
+ lines.append(line)
987
+ lines = textwrap.dedent('\n'.join(lines)).splitlines()
988
+
989
+ cmd, output = None, []
990
+ for line in lines + ['']:
991
+ is_output = line.strip() and not line.startswith(('$ ', '#'))
992
+ if cmd is not None and is_output:
993
+ output.append(line)
994
+ continue
995
+ if cmd is not None:
996
+ yield cmd, ''.join(out + '\n' for out in output)
997
+ cmd, output = None, []
998
+ if line.startswith('$ '):
999
+ cmd = line[2:]
1000
+
1001
+ def test_commandline_examples(self):
1002
+ tmpdir = tempfile.TemporaryDirectory()
1003
+ self.addCleanup(tmpdir.cleanup)
1004
+ env = dict(os.environ, PYTHONPATH=self.ROOT, PYTHONUTF8='1')
1005
+
1006
+ examples = list(self._examples('commandline.rst'))
1007
+ self.assertTrue(any(cmd.startswith('jsonpointer ')
1008
+ for cmd, _ in examples))
1009
+ for cmd, expected in examples:
1010
+ with self.subTest(cmd=cmd):
1011
+ args = shlex.split(cmd)
1012
+ if args[0] == 'cat':
1013
+ # "cat" shows the input files used by later examples
1014
+ path = os.path.join(tmpdir.name, args[1])
1015
+ with open(path, 'w', encoding='utf-8') as f:
1016
+ f.write(expected)
1017
+ continue
1018
+
1019
+ self.assertEqual(args[0], 'jsonpointer')
1020
+ result = subprocess.run([sys.executable, self.SCRIPT] + args[1:],
1021
+ cwd=tmpdir.name, env=env,
1022
+ capture_output=True, encoding='utf-8')
1023
+ self.assertEqual(result.returncode, 0, result.stderr)
1024
+ self.assertEqual(result.stdout, expected)
1025
+
1026
+
926
1027
  def load_tests(loader, tests, ignore):
927
1028
  tests.addTests(doctest.DocTestSuite(jsonpointer))
1029
+ tests.addTests(doctest.DocFileSuite('doc/tutorial.rst'))
928
1030
  return tests
@@ -1 +0,0 @@
1
- jsonpointer
File without changes
File without changes
File without changes
File without changes
File without changes