日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 把数据 json格式输出

發布時間:2025/3/19 python 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 把数据 json格式输出 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

?

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

?

import jsondate = {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"}] }

 可以看到都已經格式化了。

?

?

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

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了。

?

?

參考資料:

?

http://liuzhijun.iteye.com/blog/1859857

http://docs.python.org/2/library/json.html

http://www.cnblogs.com/coser/archive/2011/12/14/2287739.html
http://pymotw.com/2/json/

總結

以上是生活随笔為你收集整理的python 把数据 json格式输出的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。