亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

python 把數(shù)據(jù) json格式輸出的實例代碼

原創(chuàng) 2017-01-12 15:23:01 319
摘要:有個要求需要在python的標準輸出時候顯示json格式數(shù)據(jù),如果縮進顯示查看數(shù)據(jù)效果會很好,這里使用json的包會有很多操作import json   date = {u'versions': [{u'status': u'CURRENT', u'id'

有個要求需要在python的標準輸出時候顯示json格式數(shù)據(jù),如果縮進顯示查看數(shù)據(jù)效果會很好,這里使用json的包會有很多操作

import json  
date = {u'versions': [{u'status': u'CURRENT', u'id': u'v2.3', u'links': [{u'href': u'http://controller:9292/v2/', u'rel': u'self'}]}, 
{u'status': u'SUPPORTED', u'id': u'v2.2', u'links': [{u'href': u'http://controller:9292/v2/', u'rel': u'self'}]}, 
{u'status': u'SUPPORTED', u'id': u'v2.1', u'links': [{u'href': u'http://controller:9292/v2/', u'rel': u'self'}]}, 
{u'status': u'SUPPORTED', u'id': u'v2.0', u'links': [{u'href': u'http://controller:9292/v2/', u'rel': u'self'}]}, 
{u'status': u'SUPPORTED', u'id': u'v1.1', u'links': [{u'href': u'http://controller:9292/v1/', u'rel': u'self'}]}, 
{u'status': u'SUPPORTED', u'id': u'v1.0', u'links': [{u'href': u'http://controller:9292/v1/', u'rel': u'self'}]}]}  
print json.dumps(data, sort_keys=True, indent=2) # 排序并且縮進兩個字符輸出

 這樣就會得到如下的輸出:

{
 "versions": [
  {
   "id": "v2.3",
   "links": [
    {
     "href": "http://controller:9292/v2/",
     "rel": "self"
    }
   ],
   "status": "CURRENT"
  },
  {
   "id": "v2.2",
   "links": [
    {
     "href": "http://controller:9292/v2/",
     "rel": "self"
    }
   ],
   "status": "SUPPORTED"
  },
  {
   "id": "v2.1",
   "links": [
    {
     "href": "http://controller:9292/v2/",
     "rel": "self"
    }
   ],
   "status": "SUPPORTED"
  },
  {
   "id": "v2.0",
   "links": [
    {
     "href": "http://controller:9292/v2/",
     "rel": "self"
    }
   ],
   "status": "SUPPORTED"
  },
  {
   "id": "v1.1",
   "links": [
    {
     "href": "http://controller:9292/v1/",
     "rel": "self"
    }
   ],
   "status": "SUPPORTED"
  },
  {
   "id": "v1.0",
   "links": [
    {
     "href": "http://controller:9292/v1/",
     "rel": "self"
    }
   ],
   "status": "SUPPORTED"
  }
 ]
}

可以看到都已經(jīng)格式化了。

這是在python中,如果直接使用命令行,希望直接轉(zhuǎn)換,可以使用 data | python -mjson.tool 來輸出json格式的數(shù)據(jù)

echo '{"first_key": "value", "second_key": "value2"}' | python -mjson.tool   

比如想直接在命令行中過濾得到first_key對于的值,那么這樣即可:

echo '{"first_key": "value", "second_key": "value2"}' | python -c 'import sys, json; print json.load(sys.stdin)[sys.argv[1]]' first_key   

就會得到對于的value了。

更多關(guān)于python 把數(shù)據(jù) json格式輸出的實例代碼請關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!

發(fā)佈手記

熱門詞條