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

e.g.

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

推荐答案

你不能将其序列化为json,json对什么是dict键的理解远不如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相关问答推荐

按照对象键的值对PostgreSQL JSONB对象进行排序'

如何创建生成两个不同对象的JSON数组的SQL查询?

处理输入数据并转换为更简单的格式-PowerBI

无法从MongoDB集合中检索正确的文档

对一些JSON模式验证的混淆

从包含 JSON 对象序列的文件中获取第一个 JSON 对象

将 GEOSwift.JSON 转换为 Swift 中的 struct

使用 ConvertFrom-Json 后,Powershell 访问 JSON 中的嵌套对象

如何在 onClick 事件处理程序中识别在同一 map 上绘制的多个多边形中的哪个(使用 react-leaflet)被单击?

如何使用 json.net 将数据表转换为 json 字符串?

按 JSON 数据类型 postgres 排序

如何将 LinkedHashMap 转换为自定义 java 对象?

Json.Net:用于自定义命名的 JsonSerializer-Attribute

在 JSON 编码的 HTML5 数据属性中转义/编码单引号

将文件发送到 Rails JSON API

使用 ajax 将 JSON 发送到 PHP

如何在 Django JSONField 数据上聚合(最小/最大等)?

Peewee 模型转 JSON

Microsoft.Net.Http 与 Microsoft.AspNet.WebApi.Client

处理 HTTP 请求正文中的可选 JSON 字段