Skip to content

json.dump silently drops entries from dict subclasses with false truthiness #158731

Description

@augusto-rehfeldt

Bug report

Bug description:

Documented behaviour: json.dump documentation: "Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object)." JSONEncoder documentation lists "dict" as supported and maps it to JSON "object".

Expected: {"a": 1}

Actual: {}

import io, json

class D(dict):
    def __bool__(self):
        return False

d = D(a=1)
if not (D.__iter__ is dict.__iter__ and D.items is dict.items
        and all(type(k) is str and type(v) is int for k, v in d.items())
        and not bool(d) and dict(d) == {"a": 1}):
    print("REFUTATION REJECTED: invalid input")
else:
    expected = json.dumps(dict(d))
    fp = io.StringIO()
    json.dump(d, fp)
    actual = fp.getvalue()
    if actual != expected:
        print("REFUTATION CONFIRMED:", repr(d),
              "actual:", repr(actual), "expected:", repr(expected))
    else:
        print("REFUTATION REJECTED: dump preserves all entries")

Output on Python 3.14.6 (Windows-11-10.0.26220-SP0), standard library json:

REFUTATION CONFIRMED: {'a': 1} actual: '{}' expected: '{"a": 1}'

This report was found and written by an automated property-testing tool I run (bugforge). The reproducer above was executed and its output is pasted unedited; no person reviewed the report before it was filed. The search script is in https://github.com/augusto-rehfeldt/bugforge-results/tree/main/json-20261003-130022-c1

CPython versions tested on:

3.14

Operating systems tested on:

Windows

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions