Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is class that extends dict json serializable, but one that extends collections.UserDict not?

Tags:

python

json

Why class Dict(dict) is json serializable (json.dumps(Dict) works), but class Dict(collections.UserDict)is not?

like image 949
Joaquim Avatar asked Sep 14 '25 21:09

Joaquim


1 Answers

You can look at the source code for JSONEncoder and specifically this line. It checks for dict and collections.UserDict is not instance of dict.

The Encodersupports the following objects and types by default:

    +-------------------+---------------+
    | Python            | JSON          |
    +===================+===============+
    | dict              | object        |
    +-------------------+---------------+
    | list, tuple       | array         |
    +-------------------+---------------+
    | str               | string        |
    +-------------------+---------------+
    | int, float        | number        |
    +-------------------+---------------+
    | True              | true          |
    +-------------------+---------------+
    | False             | false         |
    +-------------------+---------------+
    | None              | null          |
    +-------------------+---------------+

You can extend it to handle collections.UserDict

like image 56
buran Avatar answered Sep 17 '25 10:09

buran