Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to encode tuples with json

Tags:

python

json

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.

like image 382
f4hy Avatar asked Apr 03 '09 20:04

f4hy


People also ask

How do you represent a tuple in JSON?

There is no concept of a tuple in the JSON format. Python's json module converts Python tuples to JSON lists because that's the closest thing in JSON to a tuple. Immutability will not be preserved. If you want to preserve them, use a utility like pickle or write your own encoders and decoders.

Are tuples JSON serializable Python?

Python tuples are JSON serializable, just like lists or dictionaries. The JSONEncoder class supports the following objects and types by default. The process of converting a tuple (or any other native Python object) to a JSON string is called serialization.

How do I save a JSON tuple?

To convert Python tuple to JSON, use the json. dumps() method. The json. dumps() method accepts the tuple to convert an object into a json string.

How should JSON be encoded?

The current spec says: "JSON text exchanged between systems that are not part of a closed ecosystem MUST be encoded using UTF-8.


2 Answers

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]] 
like image 185
Eli Courtwright Avatar answered Sep 19 '22 06:09

Eli Courtwright


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(',') 
like image 42
Jarret Hardie Avatar answered Sep 20 '22 06:09

Jarret Hardie