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一键升级所有pip package的方法

pip_ungrade_all.py代码如下: # -*- coding: utf-8 -*- import pip from subprocess import call f...

python实现批量文件重命名

python实现批量文件重命名

本文实例为大家分享了python批量文件重命名的具体代码,供大家参考,具体内容如下 问题描述 最近遇到朋友求助,如何将大量文件名前面的某些字符删除。 即将图中文件前的编号删除。 P...

python生成密码字典的方法

python生成密码字典的方法

这里我使用的是python27 主要用的是我之前博文里提到的itertools循环迭代的模块,用这个模块可以省不少事 首先要调用itertools import itertools...

Python使用django搭建web开发环境

Python使用django搭建web开发环境

安装 Python 去 Python 官方网站找到 Python 3 的下载地址,根据你的系统选择 32 位或者 64 位的安装包,下载好后双击安装即可。 检测是否安装完成 C:\...

pycharm激活码有效到2020年11月底

pycharm激活码有效到2020年11月底 6ZUMD7WWWU-eyJsaWNlbnNlSWQiOiI2WlVNRDdXV1dVIiwibGljZW5zZWVOYW1lIjoiSm...