Skip to content

Commit a70339f

Browse files
committed
Enclose field names containing literals in quotes
When creating the text representation of a path, field names that contain lexer literals (like a period ".') should be enclosed in quotes (or brackets). The proposed fix only adds quotes if needed (as opposed to alway). This avoids changing current paths/behavior drastically since it seems no one has run into this so far. Change-Id: Ia6e01f9b8218182aa61d3c39b16d4bfb57e4f593
1 parent de4df60 commit a70339f

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

jsonpath_ng/jsonpath.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
1-
from __future__ import unicode_literals, print_function, absolute_import, division, generators, nested_scopes
1+
from __future__ import (absolute_import, division, generators, nested_scopes,
2+
print_function, unicode_literals)
3+
24
import logging
5+
from itertools import * # noqa
6+
37
import six
48
from six.moves import xrange
5-
from itertools import * # noqa
9+
10+
from jsonpath_ng.lexer import JsonPathLexer
611

712
# Get logger name
813
logger = logging.getLogger(__name__)
@@ -539,7 +544,14 @@ def filter(self, fn, data):
539544
return data
540545

541546
def __str__(self):
542-
return ','.join(map(str, self.fields))
547+
# If any JsonPathLexer.literals are included in field name need quotes
548+
# This avoids unnecessary quotes to keep strings short.
549+
literals = JsonPathLexer.literals
550+
# Test each field whether it contains a literal and only then add quotes
551+
# The test loops over all literals, could possibly optimize to short circuit if one found
552+
fields_as_str = ("'" + str(f) + "'" if any([l in f for l in literals]) else str(f) for f in self.fields)
553+
return ','.join(fields_as_str)
554+
543555

544556
def __repr__(self):
545557
return '%s(%s)' % (self.__class__.__name__, ','.join(map(repr, self.fields)))

tests/test_jsonpath.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,8 @@ def test_child_paths(self):
232232
def test_descendants_paths(self):
233233
self.check_paths([('foo..baz', {'foo': {'baz': 1, 'bing': {'baz': 2}}}, ['foo.baz', 'foo.bing.baz'] )])
234234

235+
def test_litreals_in_field_names(self):
236+
self.check_paths([("A.'a.c'", {'A' : {'a.c': 'd'}}, ["A.'a.c'"])])
235237

236238
#
237239
# Check the "auto_id_field" feature

0 commit comments

Comments
 (0)