Skip to content

Commit

Permalink
Enclose field names containing literals in quotes
Browse files Browse the repository at this point in the history
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 always). This avoids changing current paths/behavior drastically since it seems no one has run into this so far.
  • Loading branch information
Matthias Brehler authored and michaelmior committed Sep 12, 2023
1 parent 59e6b72 commit 4c1effd
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
14 changes: 12 additions & 2 deletions jsonpath_ng/jsonpath.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from __future__ import unicode_literals, print_function, absolute_import, division, generators, nested_scopes
from __future__ import (absolute_import, division, generators, nested_scopes,
print_function, unicode_literals)

import logging
from itertools import * # noqa
from jsonpath_ng.lexer import JsonPathLexer

# Get logger name
logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -615,7 +618,14 @@ def filter(self, fn, data):
return data

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


def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, ','.join(map(repr, self.fields)))
Expand Down
2 changes: 2 additions & 0 deletions tests/test_jsonpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,8 @@ def test_child_paths(self):
def test_descendants_paths(self):
self.check_paths([('foo..baz', {'foo': {'baz': 1, 'bing': {'baz': 2}}}, ['foo.baz', 'foo.bing.baz'] )])

def test_literals_in_field_names(self):
self.check_paths([("A.'a.c'", {'A' : {'a.c': 'd'}}, ["A.'a.c'"])])

#
# Check the "auto_id_field" feature
Expand Down

0 comments on commit 4c1effd

Please sign in to comment.