python 把数据 json格式输出的实例代码

yipeiwu_com5年前Python基础

有个要求需要在python的标准输出时候显示json格式数据,如果缩进显示查看数据效果会很好,这里使用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"
  }
 ]
}

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

这是在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了。

以上就是小编为大家带来的python 把数据 json格式输出的实例代码全部内容了,希望大家多多支持【听图阁-专注于Python设计】~

相关文章

python 实现将多条曲线画在一幅图上的方法

python 实现将多条曲线画在一幅图上的方法

如下所示: # -*- coding: utf-8 -*- """ Created on Thu Jun 07 09:17:40 2018 @author: yjp """ imp...

python使用多线程不断刷新网页的方法

本文实例讲述了python使用多线程不断刷新网页的方法。分享给大家供大家参考。具体如下: 这段代码可以开通过个线程不断刷新指定的页面,可用于刷票,增加网页访问量等等,不用再去按F5了...

python基础之入门必看操作

python基础之入门必看操作

这里提供在使用python进行开发中常使用到的方法技巧,如有不对欢迎批评指正。 要点:开发中类、变量特性查询,类型就是类,断言的使用,深浅复制判断等 python脚本文件是使用UTF-8...

在Python的Django框架上部署ORM库的教程

Python ORM 概览 作为一个美妙的语言,Python 除了 SQLAlchemy 外还有很多ORM库。在这篇文章里,我们将来看看几个流行的可选ORM 库,以此更好地窥探到Pyth...

python对象转字典的两种实现方式示例

本文实例讲述了python对象转字典的两种实现方式。分享给大家供大家参考,具体如下: 一. 方便但不完美的__dict__ 对象转字典用到的方法为__dict__. 比如对象对象a的属性...