本文介绍了JSON序列化以元组为键的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
在 Python 中有没有办法序列化使用元组作为键的字典?
Is there a way in Python to serialize a dictionary that is using a tuple as key?
例如
a = {(1, 2): 'a'}
只需使用 json.dumps(a)
就会引发此错误:
simply using json.dumps(a)
raises this error:
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
推荐答案
你不能将它序列化为 json,json 对于什么是 dict 键的理解远不如 python 灵活.
You can't serialize that as json, json has a much less flexible idea about what counts as a dict key than python.
您可以将映射转换为一系列键值对,如下所示:
You could transform the mapping into a sequence of key, value pairs, something like this:
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]}]'
这篇关于JSON序列化以元组为键的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!