Python Tuple to JSON output

前端 未结 2 1000
梦毁少年i
梦毁少年i 2020-12-15 20:43

How do I turn this:

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

into this:

         


        
相关标签:
2条回答
  • 2020-12-15 21:18

    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)
    
    0 讨论(0)
  • 2020-12-15 21:28

    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.

    0 讨论(0)
提交回复
热议问题