格式化输出json格式

前言

在使用RYU控制器的Rest api时,在命令行中输入curl xxxxxxx将返回一行json数据,这样的数据可读性很差.于是,出现了chrome, firefox的rest api插件,但这需要打开浏览器,对于我这样”All in terminal” 的猿类,简直是种折磨,于是写了个python脚本,将curl获取的数据通过管道导向python脚本,进而格式化输出.

实现

fileinput模块

调用fileinput模块,使用管道将数据导向python脚本:

import fileinput
rest = fileinput.input().readline()

fileinput模块的详细实例见我的上一篇博文通过重定向,管道来作为python脚本的输入

json

通过调用json模块,可将json数据格式化输出,方便阅读.

rest = json.loads(rest)
print json.dumps(rest, indent=2)

indent表示格式化输出的缩进空格.

测试

实现代码如下:

1
2
3
4
5
6
7
import fileinput
import json

f_input=fileinput.input()
rest = f_input.readline()
rest=json.loads(rest)
print(json.dumps(rest, sort_keys=True, indent=4))

具体使用:
没用使用脚本的输出:

1
2
zp@zpeng:~$ curl http://sdn:8080/firewall/module/status
[{"status": "enable", "switch_id": "0000000000000001"}]

使用脚本后的输出:

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
zp@zpeng:~$ curl http://sdn:8080/firewall/module/status | python filein.py 
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 55 100 55 0 0 13664 0 --:--:-- --:--:-- --:--:-- 18333
[
{
"status": "enable",
"switch_id": "0000000000000001"
}
]
zp@zpeng:~$

zp@zpeng:~$ curl http://sdn:8080/firewall/rules/0000000000000001/all | python filein.py
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 365 100 365 0 0 59552 0 --:--:-- --:--:-- --:--:-- 60833
[
{
"access_control_list": [
{
"rules": [
{
"actions": "ALLOW",
"dl_type": "IPv4",
"dl_vlan": "2",
"nw_proto": "ICMP",
"nw_src": "10.0.0.0/255.0.0.0",
"priority": 1,
"rule_id": 2
},
{
"actions": "ALLOW",
"dl_type": "IPv4",
"dl_vlan": "2",
"nw_dst": "10.0.0.0/255.0.0.0",
"nw_proto": "ICMP",
"priority": 1,
"rule_id": 1
}
],
"vlan_id": "2"
}
],
"switch_id": "0000000000000001"
}
]
zp@zpeng:~$

可见使用脚本后,美化输出的目的达到了.