用JSON编码元组的最佳方法 [英] Best way to encode tuples with json
问题描述
在python中,我有一个将元组映射到元组列表的字典.例如
In python I have a dictionary that maps tuples to a list of tuples. e.g.
{(1,2): [(2,3),(1,7)]}
我希望能够使用javascript对这些数据进行编码,因此我调查了json,但发现键必须是字符串,因此我的元组不能用作键.
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上找到的内容?还是有更聪明的方法来处理这个问题.
Is the best way to handle this is encode it as "1,2" and then parse it into something I want on the javascript? Or is there a more clever way to handle this.
推荐答案
您可能会考虑说
{"[1,2]": [(2,3),(1,7)]}
,然后当您需要获取值时,您可以将键本身解析为JSON对象,所有现代浏览器都可以使用内置的JSON.parse
方法来实现(我正在使用jQuery.each
进行迭代在这里,但您可以使用任何东西):
and then when you need to get the value out, you can just parse the keys themselves as JSON objects, which all modern browsers can do with the built-in JSON.parse
method (I'm using jQuery.each
to iterate here but you could use anything):
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
您可能会说这是无效的Javascript语法
which is invalid Javascript syntax, you could say
myjson[1][2] // returns [[2,3],[1,7]]
这篇关于用JSON编码元组的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!