From 08231fb66f73b83a2b5a1acc2abef49ca3be3b4c Mon Sep 17 00:00:00 2001 From: Simon Kelly Date: Thu, 24 Jun 2021 11:21:42 +0200 Subject: don't clobber IDs if they exist If a field exists with the name of the `auto_id_field` it should be used as is without converting it to an AutoID. The auto ID functionality should only kick in if and ID field does not exist. --- jsonpath_rw/jsonpath.py | 15 +++++++-------- tests/test_jsonpath.py | 8 ++++---- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/jsonpath_rw/jsonpath.py b/jsonpath_rw/jsonpath.py index c47653e..1d4ac4c 100644 --- a/jsonpath_rw/jsonpath.py +++ b/jsonpath_rw/jsonpath.py @@ -430,14 +430,13 @@ class Fields(JSONPath): self.fields = fields def get_field_datum(self, datum, field): - if field == auto_id_field: - return AutoIdForDatum(datum) - else: - try: - field_value = datum.value[field] # Do NOT use `val.get(field)` since that confuses None as a value and None due to `get` - return DatumInContext(value=field_value, path=Fields(field), context=datum) - except (TypeError, KeyError, AttributeError): - return None + try: + field_value = datum.value[field] # Do NOT use `val.get(field)` since that confuses None as a value and None due to `get` + return DatumInContext(value=field_value, path=Fields(field), context=datum) + except (TypeError, KeyError, AttributeError): + if field == auto_id_field: + return AutoIdForDatum(datum) + return None def reified_fields(self, datum): if '*' not in self.fields: diff --git a/tests/test_jsonpath.py b/tests/test_jsonpath.py index 271e2bc..8f4ae3c 100644 --- a/tests/test_jsonpath.py +++ b/tests/test_jsonpath.py @@ -244,7 +244,7 @@ class TestJsonPath(unittest.TestCase): ('*.id', {'foo':{'id': 1}, 'baz': 2}, - set(['1', 'baz'])) ]) + set([1, 'baz'])) ]) def test_root_auto_id(self): jsonpath.auto_id_field = 'id' @@ -276,8 +276,8 @@ class TestJsonPath(unittest.TestCase): {'a': 'a1'}, {'a': 'a2', 'id': 'a2id'} ] } - self.check_cases([('m.[1].id', data, ['1.m.a2id']), - ('m.[1].$.b.id', data, ['1.bid']), + self.check_cases([('m.[1].id', data, ['a2id']), + ('m.[1].$.b.id', data, ['bid']), ('m.[0].id', data, ['1.m.[0]'])]) def test_slice_auto_id(self): @@ -290,7 +290,7 @@ class TestJsonPath(unittest.TestCase): self.check_cases([('foo.baz.id', {'foo': {'baz': 3}}, ['foo.baz']), ('foo.baz.id', {'foo': {'baz': [3]}}, ['foo.baz']), ('foo.baz.id', {'foo': {'id': 'bizzle', 'baz': 3}}, ['bizzle.baz']), - ('foo.baz.id', {'foo': {'baz': {'id': 'hi'}}}, ['foo.hi']), + ('foo.baz.id', {'foo': {'baz': {'id': 'hi'}}}, ['hi']), ('foo.baz.bizzle.id', {'foo': {'baz': {'bizzle': 5}}}, ['foo.baz.bizzle'])]) def test_descendants_auto_id(self): -- cgit v1.2.1