Skip to content

Commit f94e842

Browse files
authored
Fix JSON Schema reference collection with "examples" keys (#11325)
Backport of #11305.
1 parent 5d34efd commit f94e842

2 files changed

Lines changed: 27 additions & 3 deletions

File tree

pydantic/json_schema.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2554,8 +2554,13 @@ def _get_all_json_refs(item: Any) -> set[JsonRef]:
25542554
current = stack.pop()
25552555
if isinstance(current, dict):
25562556
for key, value in current.items():
2557-
if key == 'examples':
2558-
continue # skip examples, allow arbitrary values / refs
2557+
if key == 'examples' and isinstance(value, list):
2558+
# Skip examples that may contain arbitrary values and references
2559+
# (e.g. `{"examples": [{"$ref": "..."}]}`). Note: checking for value
2560+
# of type list is necessary to avoid skipping valid portions of the schema,
2561+
# for instance when "examples" is used as a property key. A more robust solution
2562+
# could be found, but would require more advanced JSON Schema parsing logic.
2563+
continue
25592564
if key == '$ref' and isinstance(value, str):
25602565
refs.add(JsonRef(value))
25612566
elif isinstance(value, dict):

tests/test_json_schema.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6610,7 +6610,26 @@ class Test(BaseModel):
66106610
'type': 'object',
66116611
}
66126612

6613-
# raises KeyError: '#/components/schemas/Pet'
6613+
6614+
def test_examples_as_property_key() -> None:
6615+
"""https://github.com/pydantic/pydantic/issues/11304.
6616+
6617+
A regression of https://github.com/pydantic/pydantic/issues/9981 (see `test_arbitrary_ref_in_json_schema`).
6618+
"""
6619+
6620+
class Model1(BaseModel):
6621+
pass
6622+
6623+
class Model(BaseModel):
6624+
examples: Model1
6625+
6626+
assert Model.model_json_schema() == {
6627+
'$defs': {'Model1': {'properties': {}, 'title': 'Model1', 'type': 'object'}},
6628+
'properties': {'examples': {'$ref': '#/$defs/Model1'}},
6629+
'required': ['examples'],
6630+
'title': 'Model',
6631+
'type': 'object',
6632+
}
66146633

66156634

66166635
def test_warn_on_mixed_compose() -> None:

0 commit comments

Comments
 (0)