handle duplicate JSON keys only when possible
This commit is contained in:
@@ -35,7 +35,6 @@
|
|||||||
https://github.com/json-patch/json-patch-tests """
|
https://github.com/json-patch/json-patch-tests """
|
||||||
|
|
||||||
from functools import partial
|
from functools import partial
|
||||||
import json
|
|
||||||
import doctest
|
import doctest
|
||||||
import unittest
|
import unittest
|
||||||
import jsonpatch
|
import jsonpatch
|
||||||
@@ -94,7 +93,8 @@ def get_suite(filenames):
|
|||||||
|
|
||||||
for testfile in filenames:
|
for testfile in filenames:
|
||||||
with open(testfile) as f:
|
with open(testfile) as f:
|
||||||
tests = json.load(f, object_pairs_hook=jsonpatch.multidict)
|
# we use the (potentially) patched version of json.load here
|
||||||
|
tests = jsonpatch.json.load(f)
|
||||||
cls = make_test_case(tests)
|
cls = make_test_case(tests)
|
||||||
suite.addTest(unittest.makeSuite(cls))
|
suite.addTest(unittest.makeSuite(cls))
|
||||||
|
|
||||||
|
|||||||
23
jsonpatch.py
23
jsonpatch.py
@@ -85,6 +85,27 @@ def multidict(ordered_pairs):
|
|||||||
return dict(d)
|
return dict(d)
|
||||||
|
|
||||||
|
|
||||||
|
def get_loadjson():
|
||||||
|
""" adds the object_pairs_hook parameter to json.load when possible
|
||||||
|
|
||||||
|
The "object_pairs_hook" parameter is used to handle duplicate keys when
|
||||||
|
loading a JSON object. This parameter does not exist in Python 2.6. This
|
||||||
|
methods returns an unmodified json.load for Python 2.6 and a partial
|
||||||
|
function with object_pairs_hook set to multidict for Python versions that
|
||||||
|
support the parameter. """
|
||||||
|
|
||||||
|
import inspect
|
||||||
|
import functools
|
||||||
|
|
||||||
|
argspec = inspect.getargspec(json.load)
|
||||||
|
if 'object_pairs_hook' not in argspec.args:
|
||||||
|
return json.load
|
||||||
|
|
||||||
|
return functools.partial(json.load, object_pairs_hook=multidict)
|
||||||
|
|
||||||
|
json.load = get_loadjson()
|
||||||
|
|
||||||
|
|
||||||
def apply_patch(doc, patch, in_place=False):
|
def apply_patch(doc, patch, in_place=False):
|
||||||
"""Apply list of patches to specified json document.
|
"""Apply list of patches to specified json document.
|
||||||
|
|
||||||
@@ -231,7 +252,7 @@ class JsonPatch(object):
|
|||||||
|
|
||||||
:return: :class:`JsonPatch` instance.
|
:return: :class:`JsonPatch` instance.
|
||||||
"""
|
"""
|
||||||
patch = json.loads(patch_str, object_pairs_hook=multidict)
|
patch = json.loads(patch_str)
|
||||||
return cls(patch)
|
return cls(patch)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
|
|||||||
Reference in New Issue
Block a user