Skip to content

Unambiguously quote and escape properties in JSON path rendering #1390

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion jsonschema/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from textwrap import dedent, indent
from typing import TYPE_CHECKING, Any, ClassVar
import heapq
import re
import warnings

from attrs import define
Expand All @@ -23,6 +24,8 @@
WEAK_MATCHES: frozenset[str] = frozenset(["anyOf", "oneOf"])
STRONG_MATCHES: frozenset[str] = frozenset()

_JSON_PATH_COMPATIBLE_PROPERTY_PATTERN = re.compile("^[a-zA-Z][a-zA-Z0-9_]*$")

_unset = _utils.Unset()


Expand Down Expand Up @@ -152,8 +155,11 @@ def json_path(self) -> str:
for elem in self.absolute_path:
if isinstance(elem, int):
path += "[" + str(elem) + "]"
else:
elif _JSON_PATH_COMPATIBLE_PROPERTY_PATTERN.match(elem):
path += "." + elem
else:
escaped_elem = elem.replace("\\", "\\\\").replace("'", r"\'")
path += "['" + escaped_elem + "']"
return path

def _set(
Expand Down
57 changes: 57 additions & 0 deletions jsonschema/tests/test_exceptions.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from unittest import TestCase
import textwrap

import jsonpath_ng

from jsonschema import exceptions
from jsonschema.validators import _LATEST_VERSION

Expand Down Expand Up @@ -700,3 +702,58 @@ class TestHashable(TestCase):
def test_hashable(self):
{exceptions.ValidationError("")}
{exceptions.SchemaError("")}


class TestJsonPathRendering(TestCase):
def validate_json_path_rendering(self, property_name, expected_path):
error = exceptions.ValidationError(
path=[property_name],
message="1",
validator="foo",
instance="i1",
)

rendered_json_path = error.json_path
self.assertEqual(rendered_json_path, expected_path)

re_parsed_name = jsonpath_ng.parse(rendered_json_path).right.fields[0]
self.assertEqual(re_parsed_name, property_name)

def test_basic(self):
self.validate_json_path_rendering("x", "$.x")

def test_empty(self):
self.validate_json_path_rendering("", "$['']")

def test_number(self):
self.validate_json_path_rendering("1", "$['1']")

def test_period(self):
self.validate_json_path_rendering(".", "$['.']")

def test_single_quote(self):
self.validate_json_path_rendering("'", r"$['\'']")

def test_space(self):
self.validate_json_path_rendering(" ", "$[' ']")

def test_backslash(self):
self.validate_json_path_rendering("\\", r"$['\\']")

def test_backslash_single_quote(self):
self.validate_json_path_rendering(r"\'", r"$['\\\'']")

def test_underscore(self):
self.validate_json_path_rendering("_", r"$['_']")

def test_double_quote(self):
self.validate_json_path_rendering('"', """$['"']""")

def test_hyphen(self):
self.validate_json_path_rendering("-", "$['-']")

def test_json_path_injection(self):
self.validate_json_path_rendering("a[0]", "$['a[0]']")

def test_open_bracket(self):
self.validate_json_path_rendering("[", "$['[']")
1 change: 1 addition & 0 deletions noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ def tests(session, installable):
env = dict(JSON_SCHEMA_TEST_SUITE=str(ROOT / "json"))

session.install("virtue", installable)
session.install("jsonpath-ng", installable)

if session.posargs and session.posargs[0] == "coverage":
if len(session.posargs) > 1 and session.posargs[1] == "github":
Expand Down
Loading