有没有办法在Python中序列化使用元组作为键的字典:
a={(1,2):'a'}
Run Code Online (Sandbox Code Playgroud)
简单地使用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
Run Code Online (Sandbox Code Playgroud) 在python中,我有一个将元组映射到元组列表的字典.例如
{(1,2): [(2,3),(1,7)]}
我希望能够使用javascript对这些数据进行编码,所以我查看了json,但是看起来键必须是字符串,所以我的元组不能作为键.
处理此问题的最佳方法是将其编码为"1,2",然后将其解析为我想要的javascript内容吗?或者是否有更聪明的方法来处理这个问题.