tags:

views:

759

answers:

5

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.

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.

A: 

Could it simply be a two dimensional array? Then you may use integers as keys

David Caunt
two dimensional arrays are clumsy in python, otherwise that may work.
f4hy
+1  A: 

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.

David Berger
+1  A: 

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.

Keith Gaughan
+5  A: 

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. So if you were using jQuery with the json plugin and wanted to iterate over all key/value pairs in the tuple, you'd say

var myjson = $.evalJSON('{"[1,2]": [[2,3],[1,7]]}');
$.each(myjson, function(keystr,val){
    var key = $.evalJSON(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]]
Eli Courtwright
Thanks for the idea of nested dictionaries! I wouldn't have thought of that. Not sure which approach will work better for me but seems like a neat idea, thanks!
f4hy
+4  A: 

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(',')
Jarret Hardie
Thanks for the edit nosklo... everyone needs a good editor :-)
Jarret Hardie
Cool. Thanks for the code samples too!
f4hy