In python I have a dictionary that maps tuples to a list of tuples. e.g.

{(1,2): [(2,3),(1,7)]}

I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key.

处理此问题的最佳方式是将其编码为"1,2",然后将其解析为我想要在javascript上使用的内容吗?或者有没有更聪明的方法来处理这件事.

推荐答案

你可以考虑说

{"[1,2]": [(2,3),(1,7)]}

然后,当您需要获取值时,您可以将键本身解析为JSON对象,所有现代浏览器都可以使用内置的JSON.parse方法(我在这里使用jQuery.each进行迭代,但您可以使用任何东西):

var myjson = JSON.parse('{"[1,2]": [[2,3],[1,7]]}');
$.each(myjson, function(keystr,val){
    var key = JSON.parse(keystr);
    // do something with key and val
});

On the other hand, you might want to just structure your object differently, e.g.

{1: {2: [(2,3),(1,7)]}}

因此,与其说

myjson[1,2] // doesn't work

which is invalid Javascript syntax, you could say

myjson[1][2] // returns [[2,3],[1,7]]

Json相关问答推荐

织女星-没有循环的动画条形图第二部分(实际上是织女星)

如何将响应数据保存到Flutter 中的共享首选项中

有没有办法让serde_json正确/不正确地处理NaN、inf和-inf(IEEE 754特殊标准)?

使用JQ将JSON输出转换为CSV复杂 struct

展平多个数组以保持顺序

将 json 转换为 jsonb 安全吗?

PowerShell - 将 json 添加到文件内容

使用 REACT 从字段值中读取 JSON 元素

如何将 XML 转换为 PsCustomObject 以允许最终导出为 JSON?

json.dumps 打乱了顺序

使用 c# 通用地展平 Json

什么 Python 框架用于没有前端的 REST/JSON Web 服务?

Jackson Scala 模块的小例子?

如何在 Perl 中将简单的哈希转换为 json?

如何在 MVC4 中将 Json 字符串输出为 JsonResult?

杰克逊:反序列化 for each 值都具有正确类型的 Map

未调用 npm package.json 脚本

YAML 将 5e-6 加载为字符串而不是数字

js 中奇怪的 JSON 解析行为,Unexpected token :

类型是接口或抽象类,不能实例化