Skip to content

Commit ca4ff9f

Browse files
andryakAndrea Aquino
andauthored
Fix _consume_object_or_array on unbalanced brackets in JSON strings (#621)
Co-authored-by: Andrea Aquino <[email protected]>
1 parent 67f9ae1 commit ca4ff9f

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

pydantic_settings/sources/providers/cli.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -450,8 +450,13 @@ def _consume_comma(self, item: str, merged_list: list[str], is_last_consumed_a_v
450450
def _consume_object_or_array(self, item: str, merged_list: list[str]) -> str:
451451
count = 1
452452
close_delim = '}' if item.startswith('{') else ']'
453+
in_str = False
453454
for consumed in range(1, len(item)):
454-
if item[consumed] in ('{', '['):
455+
if item[consumed] == '"' and item[consumed - 1] != '\\':
456+
in_str = not in_str
457+
elif in_str:
458+
continue
459+
elif item[consumed] in ('{', '['):
455460
count += 1
456461
elif item[consumed] in ('}', ']'):
457462
count -= 1

tests/test_source_cli.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2452,6 +2452,40 @@ class Root(BaseModel):
24522452
)
24532453

24542454

2455+
def test_cli_with_unbalanced_brackets_in_json_string():
2456+
class StrToStrDictOptions(BaseSettings):
2457+
nested: dict[str, str]
2458+
2459+
assert CliApp.run(StrToStrDictOptions, cli_args=['--nested={"test": "{"}']).model_dump() == {
2460+
'nested': {'test': '{'}
2461+
}
2462+
assert CliApp.run(StrToStrDictOptions, cli_args=['--nested={"test": "}"}']).model_dump() == {
2463+
'nested': {'test': '}'}
2464+
}
2465+
assert CliApp.run(StrToStrDictOptions, cli_args=['--nested={"test": "["}']).model_dump() == {
2466+
'nested': {'test': '['}
2467+
}
2468+
assert CliApp.run(StrToStrDictOptions, cli_args=['--nested={"test": "]"}']).model_dump() == {
2469+
'nested': {'test': ']'}
2470+
}
2471+
2472+
class StrToListDictOptions(BaseSettings):
2473+
nested: dict[str, list[str]]
2474+
2475+
assert CliApp.run(StrToListDictOptions, cli_args=['--nested={"test": ["{"]}']).model_dump() == {
2476+
'nested': {'test': ['{']}
2477+
}
2478+
assert CliApp.run(StrToListDictOptions, cli_args=['--nested={"test": ["}"]}']).model_dump() == {
2479+
'nested': {'test': ['}']}
2480+
}
2481+
assert CliApp.run(StrToListDictOptions, cli_args=['--nested={"test": ["["]}']).model_dump() == {
2482+
'nested': {'test': ['[']}
2483+
}
2484+
assert CliApp.run(StrToListDictOptions, cli_args=['--nested={"test": ["]"]}']).model_dump() == {
2485+
'nested': {'test': [']']}
2486+
}
2487+
2488+
24552489
def test_cli_json_optional_default():
24562490
class Nested(BaseModel):
24572491
foo: int = 1

0 commit comments

Comments
 (0)