jsonpointer 3.3__tar.gz → 3.5__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jsonpointer
3
- Version: 3.3
3
+ Version: 3.5
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
@@ -13,7 +13,7 @@ parser = argparse.ArgumentParser(
13
13
  # Accept pointer as option, as file or as first positional argument
14
14
  ptr_group = parser.add_mutually_exclusive_group()
15
15
 
16
- ptr_group.add_argument('-f', '--pointer-file', type=argparse.FileType('r'),
16
+ ptr_group.add_argument('-f', '--pointer-file', type=argparse.FileType('r', encoding='utf-8'),
17
17
  help='File containing a JSON pointer expression')
18
18
 
19
19
  ptr_group.add_argument('-p', '--pointer', type=str,
@@ -88,7 +88,7 @@ def resolve_files():
88
88
 
89
89
  for name in files:
90
90
  try:
91
- f = argparse.FileType('r')(name)
91
+ f = argparse.FileType('r', encoding='utf-8')(name)
92
92
  except argparse.ArgumentTypeError as e:
93
93
  parser.error(str(e))
94
94
 
@@ -104,6 +104,9 @@ def resolve_files():
104
104
 
105
105
  try:
106
106
  result = jsonpointer.resolve_pointer(doc, ptr)
107
+ if isinstance(result, jsonpointer.EndOfList):
108
+ raise jsonpointer.JsonPointerException(
109
+ "'-' does not reference an existing array element")
107
110
  print(json.dumps(result, indent=args.indent))
108
111
  except jsonpointer.JsonPointerException as e:
109
112
  print('Could not resolve pointer: %s' % str(e), file=sys.stderr)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jsonpointer
3
- Version: 3.3
3
+ Version: 3.5
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
@@ -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.3'
35
+ __version__ = '3.5'
36
36
  __website__ = 'https://github.com/stefankoegl/python-json-pointer'
37
37
  __license__ = 'Modified BSD License'
38
38
 
@@ -48,12 +48,17 @@ _nothing = object()
48
48
  VERBOSE_EXCEPTIONS = True
49
49
 
50
50
 
51
- def set_pointer(doc, pointer, value, inplace=True):
51
+ def set_pointer(doc, pointer, value, inplace=True, create=False):
52
52
  """Resolves a pointer against doc and sets the value of the target within doc.
53
53
 
54
54
  With inplace set to true, doc is modified as long as pointer is not the
55
55
  root.
56
56
 
57
+ With create set to true, missing intermediate members are created as
58
+ dicts instead of raising a JsonPointerException. A missing intermediate
59
+ array element can be created by referencing the end of the array, either
60
+ with "-" or with an index equal to the length of the array.
61
+
57
62
  >>> obj = {'foo': {'anArray': [ {'prop': 44}], 'another prop': {'baz': 'A string' }}}
58
63
 
59
64
  >>> set_pointer(obj, '/foo/anArray/0/prop', 55) == \
@@ -68,10 +73,14 @@ def set_pointer(doc, pointer, value, inplace=True):
68
73
  >>> set_pointer(obj, '/foo/a%20b', 'x') == \
69
74
  {'foo': {'a%20b': 'x' }}
70
75
  True
76
+
77
+ >>> set_pointer({}, '/cat/name', 'whiskers', create=True) == \
78
+ {'cat': {'name': 'whiskers'}}
79
+ True
71
80
  """
72
81
 
73
82
  pointer = JsonPointer(pointer)
74
- return pointer.set(doc, value, inplace)
83
+ return pointer.set(doc, value, inplace, create)
75
84
 
76
85
 
77
86
  def resolve_pointer(doc, pointer, default=_nothing):
@@ -200,8 +209,11 @@ class JsonPointer:
200
209
 
201
210
  get = resolve
202
211
 
203
- def set(self, doc, value, inplace=True):
204
- """Resolve the pointer against the doc and replace the target with value."""
212
+ def set(self, doc, value, inplace=True, create=False):
213
+ """Resolve the pointer against the doc and replace the target with value.
214
+
215
+ With create set to true, missing intermediate members are created as
216
+ dicts (see set_pointer)."""
205
217
 
206
218
  if len(self.parts) == 0:
207
219
  if inplace:
@@ -211,20 +223,67 @@ class JsonPointer:
211
223
  if not inplace:
212
224
  doc = copy.deepcopy(doc)
213
225
 
214
- (parent, part) = self.to_last(doc)
226
+ if create:
227
+ parent = doc
228
+ for i, part in enumerate(self.parts[:-1]):
229
+ part = self._get_create_part(parent, part)
230
+ if self._is_missing(parent, part):
231
+ # Everything below this point is new, so build the
232
+ # missing structure detached and attach it in one step.
233
+ # This leaves doc unchanged if anything goes wrong.
234
+ child = value
235
+ for missing in reversed(self.parts[i + 1:]):
236
+ child = {missing: child}
237
+ self._set_child(parent, part, child)
238
+ return doc
239
+ parent = self.walk(parent, part)
240
+ part = self._get_create_part(parent, self.parts[-1])
241
+ else:
242
+ (parent, part) = self.to_last(doc)
243
+
244
+ self._set_child(parent, part, value)
245
+ return doc
246
+
247
+ @classmethod
248
+ def _get_create_part(cls, doc, part):
249
+ """Like get_part, but maps an index just past the end of a sequence
250
+ to "-" so that it is appended"""
251
+
252
+ part = cls.get_part(doc, part)
253
+ if isinstance(doc, Sequence) and part == len(doc):
254
+ return '-'
255
+ return part
256
+
257
+ @staticmethod
258
+ def _is_missing(doc, part):
259
+ """Returns True if part does not exist in doc but could be added"""
260
+
261
+ if isinstance(doc, Mapping):
262
+ return part not in doc
263
+
264
+ if isinstance(doc, Sequence) and not isinstance(doc, str):
265
+ return part == '-'
266
+
267
+ return False
268
+
269
+ @staticmethod
270
+ def _set_child(parent, part, value):
271
+ """Sets parent[part] to value, appending for the end of a sequence"""
215
272
 
216
273
  if isinstance(parent, str):
217
274
  raise JsonPointerException("Cannot set value in a string")
218
275
  elif isinstance(parent, Sequence) and part == '-':
219
- parent.append(value)
276
+ try:
277
+ parent.append(value)
278
+ except AttributeError as e:
279
+ # immutable sequences, such as tuples, can't be appended to
280
+ raise JsonPointerException("Invalid assignment target: %s" % (e,))
220
281
  else:
221
282
  try:
222
283
  parent[part] = value
223
284
  except (TypeError, IndexError) as e:
224
285
  raise JsonPointerException("Invalid assignment target: %s" % (e,))
225
286
 
226
- return doc
227
-
228
287
  @classmethod
229
288
  def get_part(cls, doc, part):
230
289
  """Returns the next step in the correct type"""
@@ -2,6 +2,7 @@
2
2
 
3
3
  import copy
4
4
  import doctest
5
+ import json
5
6
  import os
6
7
  import subprocess
7
8
  import sys
@@ -386,6 +387,69 @@ class SetTests(unittest.TestCase):
386
387
 
387
388
  self.assertRaises(JsonPointerException, set_pointer, doc, "", 9)
388
389
 
390
+ def test_set_create(self):
391
+ doc = {}
392
+ set_pointer(doc, "/cat/name", "whiskers", create=True)
393
+ self.assertEqual(doc, {"cat": {"name": "whiskers"}})
394
+
395
+ doc = {"cities": {"NewYork": "0"}}
396
+ set_pointer(doc, "/cities/LosAngeles/population", "4mln", create=True)
397
+ self.assertEqual(doc, {"cities": {
398
+ "NewYork": "0",
399
+ "LosAngeles": {"population": "4mln"},
400
+ }})
401
+
402
+ # existing members are kept
403
+ set_pointer(doc, "/cities/LosAngeles/area", 1302, create=True)
404
+ self.assertEqual(doc["cities"]["LosAngeles"],
405
+ {"population": "4mln", "area": 1302})
406
+
407
+ def test_set_create_not_inplace(self):
408
+ doc = {"a": {}}
409
+ newdoc = set_pointer(doc, "/a/b/c", 1, inplace=False, create=True)
410
+ self.assertEqual(newdoc, {"a": {"b": {"c": 1}}})
411
+ self.assertEqual(doc, {"a": {}})
412
+
413
+ def test_set_create_list(self):
414
+ doc = {"foo": []}
415
+ set_pointer(doc, "/foo/-/bar", 1, create=True)
416
+ self.assertEqual(doc, {"foo": [{"bar": 1}]})
417
+
418
+ set_pointer(doc, "/foo/1/bar", 2, create=True)
419
+ self.assertEqual(doc, {"foo": [{"bar": 1}, {"bar": 2}]})
420
+
421
+ set_pointer(doc, "/foo/0/baz", 3, create=True)
422
+ self.assertEqual(doc, {"foo": [{"bar": 1, "baz": 3}, {"bar": 2}]})
423
+
424
+ set_pointer(doc, "/foo/2", 4, create=True)
425
+ self.assertEqual(doc, {"foo": [{"bar": 1, "baz": 3}, {"bar": 2}, 4]})
426
+
427
+ def test_set_create_invalid(self):
428
+ doc = {"foo": [1], "s": "str"}
429
+ # indices past the end of a list can't be created
430
+ self.assertRaises(JsonPointerException, set_pointer, doc,
431
+ "/foo/5/bar", 1, create=True)
432
+ # nothing can be created inside a string
433
+ self.assertRaises(JsonPointerException, set_pointer, doc,
434
+ "/s/bar/baz", 1, create=True)
435
+ self.assertEqual(doc, {"foo": [1], "s": "str"})
436
+
437
+ def test_set_create_immutable_sequence(self):
438
+ doc = {"items": ()}
439
+ self.assertRaises(JsonPointerException, set_pointer, doc,
440
+ "/items/0/leaf", 7, create=True)
441
+ self.assertRaises(JsonPointerException, set_pointer, doc,
442
+ "/items/0", 7, create=True)
443
+ self.assertRaises(JsonPointerException, set_pointer, doc,
444
+ "/items/-", 7)
445
+ self.assertEqual(doc, {"items": ()})
446
+
447
+ def test_set_create_off_by_default(self):
448
+ doc = {}
449
+ self.assertRaises(JsonPointerException, set_pointer, doc,
450
+ "/cat/name", "whiskers")
451
+ self.assertEqual(doc, {})
452
+
389
453
 
390
454
  class AltTypesTests(unittest.TestCase):
391
455
  class Node(object):
@@ -503,14 +567,33 @@ class CommandLineTests(unittest.TestCase):
503
567
  self._write('ptr.txt', '/a\n')
504
568
 
505
569
  def _write(self, name, content):
506
- with open(os.path.join(self.dir, name), 'w') as f:
570
+ with open(os.path.join(self.dir, name), 'w', encoding='utf-8') as f:
507
571
  f.write(content)
508
572
 
509
- def _run(self, *args):
573
+ def _run(self, *args, utf8=True):
510
574
  env = dict(os.environ, PYTHONPATH=self.ROOT, PYTHONUTF8='1')
575
+ if not utf8:
576
+ # Keep pipes in UTF-8 while exercising locale-dependent file I/O.
577
+ env.update(PYTHONUTF8='0', PYTHONIOENCODING='utf-8',
578
+ LC_ALL='C', PYTHONCOERCECLOCALE='0')
511
579
  return subprocess.run([sys.executable, self.SCRIPT] + list(args),
512
580
  cwd=self.dir, env=env, capture_output=True,
513
- text=True)
581
+ encoding='utf-8')
582
+
583
+ def test_utf8_json_file_without_utf8_mode(self):
584
+ self._write('unicode.json', '{"value": "🚀"}')
585
+ proc = self._run('/value', 'unicode.json', utf8=False)
586
+ self.assertEqual(proc.returncode, 0, proc.stderr)
587
+ self.assertEqual(json.loads(proc.stdout), '🚀')
588
+ self.assertEqual(proc.stderr, '')
589
+
590
+ def test_utf8_pointer_file_without_utf8_mode(self):
591
+ self._write('unicode.json', json.dumps({'ä': 'expected'}))
592
+ self._write('unicode.txt', '/ä\n')
593
+ proc = self._run('-f', 'unicode.txt', 'unicode.json', utf8=False)
594
+ self.assertEqual(proc.returncode, 0, proc.stderr)
595
+ self.assertEqual(json.loads(proc.stdout), 'expected')
596
+ self.assertEqual(proc.stderr, '')
514
597
 
515
598
  def test_positional_pointer(self):
516
599
  proc = self._run('/a', 'a.json', 'b.json')
@@ -576,6 +659,36 @@ class CommandLineTests(unittest.TestCase):
576
659
  self.assertIn('Could not resolve pointer', proc.stderr)
577
660
  self.assertEqual(proc.stdout, '')
578
661
 
662
+ def test_end_of_list_pointer(self):
663
+ for content, pointer in (('[]', '/-'), ('[1, 2]', '/-'),
664
+ ('{"a": []}', '/a/-')):
665
+ with self.subTest(content=content, pointer=pointer):
666
+ self._write('array.json', content)
667
+ proc = self._run(pointer, 'array.json')
668
+ self.assertEqual(proc.returncode, 1)
669
+ self.assertEqual(proc.stdout, '')
670
+ self.assertIn('Could not resolve pointer:', proc.stderr)
671
+ self.assertNotIn('Traceback', proc.stderr)
672
+
673
+ def test_end_of_list_pointer_in_one_file(self):
674
+ self._write('array.json', '{"a": []}')
675
+ self._write('member.json', '{"a": {"-": "value"}}')
676
+ for files in (('array.json', 'member.json'),
677
+ ('member.json', 'array.json')):
678
+ with self.subTest(files=files):
679
+ proc = self._run('/a/-', *files)
680
+ self.assertEqual(proc.returncode, 1)
681
+ self.assertEqual(proc.stdout, '"value"\n')
682
+ self.assertIn('Could not resolve pointer:', proc.stderr)
683
+ self.assertNotIn('Traceback', proc.stderr)
684
+
685
+ def test_hyphen_object_member(self):
686
+ self._write('member.json', '{"-": [1, 2]}')
687
+ proc = self._run('/-', 'member.json')
688
+ self.assertEqual(proc.returncode, 0, proc.stderr)
689
+ self.assertEqual(proc.stdout, '[1, 2]\n')
690
+ self.assertEqual(proc.stderr, '')
691
+
579
692
  def test_unresolvable_pointer_in_one_file(self):
580
693
  # /b resolves in b.json only; a.json is still reported but b.json
581
694
  # is processed
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes