脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 把数据 json格式输出的实例代码

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

2020-09-11 09:35脚本之家 Python

下面小编就为大家带来一篇python 把数据 json格式输出的实例代码。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

有个要求需要在python的标准输出时候显示json格式数据,如果缩进显示查看数据效果会很好,这里使用json的包会有很多操作

?
1
2
3
4
5
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) # 排序并且缩进两个字符输出

 这样就会得到如下的输出:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
{
 "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格式的数据

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

比如想直接在命令行中过滤得到first_key对于的值,那么这样即可:

?
1
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格式输出的实例代码全部内容了,希望大家多多支持服务器之家~

延伸 · 阅读

精彩推荐