Best way to encode tuples with json

Solution 1:

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

Solution 2:

If your key tuples are truly integer pairs, then the easiest and probably most straightforward approach would be as you suggest.... encode them to a string. You can do this in a one-liner:

>>> simplejson.dumps(dict([("%d,%d" % k, v) for k, v in d.items()]))
'{"1,2": [[2, 3], [1, 7]]}'

This would get you a javascript data structure whose keys you could then split to get the points back again:

'1,2'.split(',')

Solution 3:

My recommendation would be:

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

It's still parsing, but depending on how you use it, it may be easier in this form.

Solution 4:

You can't use an array as a key in JSON. The best you can do is encode it. Sorry, but there's really no other sane way to do it.