Skip to content

Fail json_dumps when an object key cannot be written - #772

Open
pargue wants to merge 1 commit into
akheron:masterfrom
pargue:fix/dump-object-key-error
Open

pargue wants to merge 1 commit into
akheron:masterfrom
pargue:fix/dump-object-key-error

Conversation

@pargue

@pargue pargue commented Nov 2, 2026

Copy link
Copy Markdown

Fail json_dumps when an object key cannot be written

Fixes #655.

do_dump ignores dump_string's return value for object keys, on both the JSON_SORT_KEYS and the unsorted path. When the output buffer cannot grow for a long key, the key is dropped, but the ": " and the value after it are small enough to fit, so json_dumps returns malformed JSON such as {": 1, "a": 2} instead of NULL.

This checks dump_string's result at both sites, as is already done for string values.

Behaviour change: two cases now make json_dumps / json_dump_callback / json_dumpf fail instead of producing malformed output:

  • a key that cannot be written: out of memory, or a dump callback or file write that returns an error. The callback docs already say returning -1 stops the encoding; for keys it did not.
  • a key that is not valid UTF-8. Only the _nocheck setters can create one. On master {"ab\xff": 1, "x": 2} dumps as {": 1, "x": 2}; it now fails, the same as an invalid string value.

json_dumpb is unaffected (its callback never fails). The sorted path still frees its key array on the new early return.

Tests in test/suites/api/test_dump.c: dump_key_out_of_memory dumps an object with a 4 KB key through an allocator that refuses blocks over 1 KB, and dump_key_invalid_utf8 dumps one with an invalid UTF-8 key, each sorted and unsorted. Both fail on master and pass with the fix. The full suite passes (215 tests), also under ASan/UBSan.

do_dump ignored dump_string's return value for object keys, on both the
JSON_SORT_KEYS and the unsorted path. When the output buffer could not
grow for a long key, the key was dropped, but the ": " and the value
after it were small enough to fit, so json_dumps returned malformed
JSON such as {": 1, "a": 2} instead of NULL.

Check dump_string's result at both sites, as is already done for string
values. Two things now fail the dump instead of producing malformed
output: a key that cannot be written (out of memory, or a dump callback
or file write that returns an error), and a key that is not valid UTF-8,
which only the _nocheck setters can create.

Tests: an object with a 4 KB key dumped through an allocator that
refuses large blocks, and an object with an invalid UTF-8 key, each
sorted and unsorted.

Fixes akheron#655.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.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.

dump_string func can error return

1 participant