#8714·datasets

Casting mixed JSON and plain strings to Json depends on row order and batch size

Author: Marcuswang0824Created Sep 30, 2026Updated Sep 30, 2026

Describe the bug

Casting a string column containing both JSON-encoded values and plain strings to Json() gives different results depending on row order and batch_size. A plain string among the first five rows makes valid JSON values decode as strings; a plain string after those rows is left unencoded and raises ValueError when read.

Dataset.from_dict(..., features=Features({"value": Json()})) handles the same values correctly. Json.cast_storage samples only the first five values, then treats the entire array as either encoded or unencoded. Applying the existing Json.encode_example rule separately to each string fixes both cases.

Related open PRs #8682 (large_string/string_view handling) and #8712 (struct child null masks) address different triggers. This reproduction uses an ordinary, top-level Value("string") column. It is also separate from #8713, which concerns preserving literal strings during automatic JSON-loader inference. Here Json() is explicitly requested and the expected behavior matches its existing single-value encoding rule.

Prepared and tested with the help of Codex.

Steps to reproduce the bug

python
from datasets import Dataset, Features, Json

features = Features({"value": Json()})
for values in (["hello"] + ["{}"] * 5, ["{}"] * 5 + ["hello"]):
    print("direct:", Dataset.from_dict({"value": values}, features=features)["value"][:])
    for batch_size in (1, 3, 1000):
        ds = Dataset.from_dict({"value": values}).cast(features, batch_size=batch_size)
        try:
            print("cast:", batch_size, ds["value"][:])
        except ValueError as error:
            print("cast:", batch_size, type(error).__name__, str(error))

For ["hello"] + ["{}"] * 5, a batch size of 1000 returns ['hello', '{}', '{}', '{}', '{}', '{}'] instead of ['hello', {}, {}, {}, {}, {}].

For ["{}"] * 5 + ["hello"], a batch size of 1000 raises ValueError: Expected object or value. A batch size of 1 handles both orders correctly.

Expected behavior

Explicit casts to Json() should follow the existing per-value encoding behavior regardless of neighboring rows or batch size: preserve valid JSON text, encode plain strings as JSON strings, and preserve Arrow nulls. Reading the cast dataset should return the same values as constructing it with the same explicit Json() feature.

Environment info

  • Datasets: 5.0.2.dev0, main at fa995bdaea171d50d086743364f23e9db6b557d8
  • Python: 3.12.14
  • PyArrow: 25.0.1
  • pandas: 3.0.6
  • OS: macOS arm64
  • Local reproduction; no Hub credentials, downloads, GPU, or API calls required.