一尘不染

json以元组为键序列化字典

json

Python中是否有一种方法可以序列化使用元组作为键的字典:

a={(1,2):'a'}

只需使用json.dumps(a),就会产生:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/json/__init__.py", line 230, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python2.6/json/encoder.py", line 367, in encode
    chunks = list(self.iterencode(o))
  File "/usr/lib/python2.6/json/encoder.py", line 309, in _iterencode
    for chunk in self._iterencode_dict(o, markers):
  File "/usr/lib/python2.6/json/encoder.py", line 268, in _iterencode_dict
    raise TypeError("key {0!r} is not a string".format(key))
TypeError: key (1, 2) is not a string

阅读 307

收藏
2020-07-27

共1个答案

一尘不染

您不能将其序列化为json,json对于什么算作dict键要比python灵活得多。

您可以将映射转换为键,值对的序列,如下所示:

>>> import json
>>> def remap_keys(mapping):
...     return [{'key':k, 'value': v} for k, v in mapping.iteritems()]
... 
>>> json.dumps(remap_keys({(1, 2): 'foo'}))
'[{"value": "foo", "key": [1, 2]}]'
2020-07-27