Skip to content

Fix to_json(lines=False) producing invalid JSON for multi-batch datasets#8314

Open
Functionhx wants to merge 1 commit into
huggingface:mainfrom
Functionhx:fix/to-json-lines-false
Open

Fix to_json(lines=False) producing invalid JSON for multi-batch datasets#8314
Functionhx wants to merge 1 commit into
huggingface:mainfrom
Functionhx:fix/to-json-lines-false

Conversation

@Functionhx

Copy link
Copy Markdown

Fixes #7037.

to_json(lines=False) concatenated batch JSON arrays directly (like [...][...][...]), which is invalid JSON. Fixed by stripping outer brackets from each batch with orient=records and wrapping in a single array.

When to_json(lines=False) is called on a dataset larger than the batch
size, each batch produced a complete JSON array (e.g. [{...}, {...}]),
and these were concatenated directly in _write, producing
[{...}][{...}] which is invalid JSON.

For orient="records" (the default), fix by stripping the outer [ and ]
from each batch output and wrapping all batch contents in a single
JSON array.

For other orient values where batching does not naturally produce
concatenable output, load the full dataset into a single DataFrame and
write once.

Remove the NotImplementedError guard that previously blocked this
combination because the underlying issue is now fixed.

Root cause: _batch_json calls pandas.DataFrame.to_json which produces
a self-contained JSON string, but _write blindly concatenated these
strings without accounting for the array structure.

Test Plan:
- Ran existing test suite: 18/18 tests pass (tests/io/test_json.py)
- Manually verified with dataset of 2500 rows exceeding batch_size
  across orient="records", orient="split", and lines=True
  regression. All produce valid, parseable JSON.

Signed-off-by: Yuchen Fan <functionhx@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A bug of Dataset.to_json() function

1 participant