Best way to encode tuples with json

后端 未结 5 1859
有刺的猬
有刺的猬 2021-02-05 00:23

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 j

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-05 01:06

    You might consider saying

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

    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)]}}
    

    so that instead of saying

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

    which is invalid Javascript syntax, you could say

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

提交回复
热议问题