广州鸿名健康科技有限公司


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

网络编程 python 把数据 json格式输出的实例代码 06-22

有个要求需要在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格式输出的实例代码全部内容了,希望大家多多支持积木网~

浅谈django中的认证与登录
认证登录django.contrib.auth中提供了许多方法,这里主要介绍其中的三个:1authenticate(**credentials)提供了用户认证,即验证用户名以及密码是否正确一般需要

python字典多键值及重复键值的使用方法(详解)
在Python中使用字典,格式如下:dict={key1:value1,key2;value2...}在实际访问字典值时的使用格式如下:dict[key]多键值字典的多键值形式如下:dict={(ke11,key12):va

Python 性能优化技巧总结
1.使用测量工具,量化性能才能改进性能,常用的timeit和memory_profiler,此外还有profile、cProfile、hotshot等,memory_profiler用了psutil,所以不能跟踪cpython的扩


编辑:广州鸿名健康科技有限公司

标签:格式,键值,字典,就会,数据