Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Tuple to JSON output

Tags:

python

json

How do I turn this:

data = ((1, '2011-01-01'), (2, '2011-01-02'), (1, '2011-01-15'), (3, '2011-02-01'))

into this:

{
    "item": [
     "1",
     "2",
     "1",
     "3",
    ],
    "settings": {
     "axisx": [
      "2011-01-01",
      "2011-01-02",
      "2011-01-15",
      "2011-02-01"
     ],
     "axisy": [
      "0",
      "100"
     ],
     "colour": "ff9900"
     }
}

Or rather, are there any helpful resources that I can read so that I would be able to produce that JSON output? So I know I need to 'transform' my data into the right data structure. After that is it as easy as json.dumps(data)

Thanks

like image 393
super9 Avatar asked Feb 23 '11 07:02

super9


People also ask

How do you pass a tuple in JSON Python?

Create a variable to store the input tuple. Use the json. dumps() function(converts a Python tuple to JSON) for converting input tuple into JSON string by passing the input tuple as an argument to it. Print the resultant JSON string object.

Can you serialize a tuple 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.


2 Answers

Use the json library.

Then convert your data using something like this:

somedict = { "item"     : [ x[0] for x in data ],
             "settings" : { "axisx" : [ x[1] for x in data ],
                            "axisy" : [ 0, 100],
                            "colour" : "ff9900" }
           }

and call:

print json.dumps(somedict)
like image 122
phooji Avatar answered Nov 06 '22 02:11

phooji


There is a json library.

import json

jsonObj = json.dumps(data)

Thats for json serializing. If you want output be formatted in some other way than you initial data variable, you should create another object, initialize it with values from data in the way you need and than use json library for serialization.

like image 13
Alexander Sobolev Avatar answered Nov 06 '22 03:11

Alexander Sobolev