Skip to content

JSON serialization doesn't work when DeepDiff is part of another dict #566

@maltelorbach

Description

@maltelorbach

Describe the bug
When the DeepDiff object is part of another dictionary, I can't get the serialization to work. Perhaps it's more the json/Python part of it and any suggestions are welcome.

Details
The .to_json() works fine for a standalone DeepDiff object, but in my case it is part of a larger data structure that I want to serialize to json.

I tried using the .to_json() method in a custom JSONEncoder, but as it turns out the custom encoder doesn't receive the DeepDiff object but a SetUnordered for which no serialization is known.

To Reproduce
MWE:

import json

from deepdiff import DeepDiff

d1 = dict(a=1, b=2, c=3)
d2 = dict(a=1, b=2, c=4, e="new")

diff = DeepDiff(d1, d2)

print(diff.to_json())  # works fine

# ---

some_bigger_object = {"diffs": diff}


class DeepDiffToDictEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, DeepDiff):
            return o.to_dict()
        return super().default(o)


class DeepDiffToJsonEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, DeepDiff):
            return o.to_json()
        return super().default(o)


# raises TypeError: Object of type SetOrdered is not JSON serializable
print(json.dumps(some_bigger_object, cls=DeepDiffToDictEncoder))

# raises TypeError: Object of type SetOrdered is not JSON serializable
print(json.dumps(some_bigger_object, cls=DeepDiffToJsonEncoder))

Expected behavior
I expect that - using a custom JSONEncoder - it should be possible to serialize a data structure containing a DeepDiff object.

OS, DeepDiff version and Python version (please complete the following information):

  • OS: Ubuntu
  • Version [24]
  • Python Version [3.13]
  • DeepDiff Version [8.6.0]

Workaround
For now I'm using the following workaround when creating my larger data structure:

some_bigger_object = {"diffs": json.loads(diff.to_json())}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions