Python元组转JSON输出 [英] Python Tuple to JSON output

查看:108
本文介绍了Python元组转JSON输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何转动:

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

对此:

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

或者说,有没有什么我可以阅读的有用资源,以便能够生成该JSON输出?所以我知道我需要将我的数据转换"为正确的数据结构.之后,就像json.dumps(data)

一样简单

谢谢

解决方案

使用 json库.

然后使用类似以下的方式转换您的数据:

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

并致电:

print json.dumps(somedict)

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

解决方案

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)

这篇关于Python元组转JSON输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆