# Json does not support Mapping and MutableMapping

**URL:** <https://discuss.python.org/t/json-does-not-support-mapping-and-mutablemapping/2829>\
**Category:** Python Help\
**Created:** [December 10, 2019, 6:07pm UTC](https://discuss.python.org/t/json-does-not-support-mapping-and-mutablemapping/2829 "2019-12-10T18:07:27Z")\
**Posts on this page:** 1\
**Showing post:** 7

<div class="post-metadata">

**Author:** ![methane](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/methane/32/43_2.png) [@methane](https://discuss.python.org/u/methane)\
**Post date:** [December 11, 2019, 10:37am UTC](https://discuss.python.org/t/json-does-not-support-mapping-and-mutablemapping/2829/7 "2019-12-11T10:37:36Z")

</div>

> [@Marco\_Sulla](#):
>
> ? Why? Usually who creates a Mapping uses a private `dict` attribute, and ` __iter__ ` usually returns `iter(self._dict)`

When iterating `dict`, json module iterate the internal structure of the dict direclty. (e.g. `PyDict_Iter`) It is very fast.  
On the other hand, when iterating Mapping, it does:

```py
for key in m.keys():
    value = mapping[key]
    serialize_map(key, value)

```

Since `m. __getitem__ ` is implemented in Python, we need one Python call per iterating each item.

Calling Python method is much slower than iterating C array.

```auto
$ pyperf timeit -s 'd = dict.fromkeys(range(1000))' -- 'dict(d)'
.....................
Mean +- std dev: 18.8 us +- 0.2 us

$ pyperf timeit -s 'import collections; d = collections.UserDict.fromkeys(range(1000))' -- 'dict(d)'
.....................
Mean +- std dev: 208 us +- 1 us

$ pyperf timeit -s 'import collections; d = collections.UserDict.fromkeys(range(1000))' -- 'dict(d.data)'
.....................
Mean +- std dev: 18.8 us +- 0.2 us

```

> [@Marco\_Sulla](#):
>
> …why? o\_\_\_0

See this example. If we serialize arbitrary Mapping, this example will not work.

```auto
class MyMapping(abc.Mapping):
    def __init__ (self, dict):
        self._data = dict
    ...

def custom_serialize(obj):
    if isinsintance(obj, MyMapping):
        d = {" __type__": "MyMapping"}
        d.update(obj._data)
        return d
    ...

J = json.dumps(someobj, default=custom_serialize)

...

def custom_deserialize(d):
    if d.get(" __type__") == "MyMapping":
        del d[" __type__"]
        return MyMapping(d)
    return d

....

json.loads(J, object_hook=custom_deserialize)

```

---

_[View the full topic](https://discuss.python.org/t/json-does-not-support-mapping-and-mutablemapping/2829)._
