Skip to content

Commit

Permalink
Fixed #80 - comma could start json list
Browse files Browse the repository at this point in the history
  • Loading branch information
noamgat committed Mar 1, 2024
1 parent 653b0d0 commit ba64f78
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lmformatenforcer/jsonschemaparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -615,15 +615,15 @@ def can_end(self) -> bool:
def get_allowed_control_characters(self):
num_items = self.num_items_seen
is_on_top = self.root.context.active_parser.object_stack[-1] == self
if (not is_on_top) and self.root.last_non_whitespace_character != "[":
if (not is_on_top) and self.root.context.active_parser.last_non_whitespace_character != "[":
# If there is an active parser above us, and the last character is not [,
# there is an active item parser on the stack that we did not count yet.
num_items += 1
control_characters = ""
has_enough_items = self.min_items is None or num_items >= self.min_items
can_add_another_item = self.max_items is None or num_items < self.max_items

if can_add_another_item:
if num_items > 0 and can_add_another_item:
control_characters += ","
if has_enough_items:
control_characters += "]"
Expand Down
10 changes: 10 additions & 0 deletions tests/test_jsonschemaparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,3 +344,13 @@ class EmptyListOKModel(BaseModel):

no_strings = '{"num":1,"list_of_strings":[\n]}'
_test_json_schema_parsing_with_string(no_strings, EmptyListOKModel.model_json_schema(), True)


def test_comma_cannot_start_list():
class FlightRoute(BaseModel):
airports: List[str]
output_notok = """ { "airports": [,"name"] } """
output_ok = """ { "airports": ["name"] } """

_test_json_schema_parsing_with_string(output_ok, FlightRoute.model_json_schema(), True)
_test_json_schema_parsing_with_string(output_notok, FlightRoute.model_json_schema(), False)

0 comments on commit ba64f78

Please sign in to comment.