【Linux学习】jq:一款json格式化神器
什么是jq?jq是Linux下面把文本字符串格式化成json格式的工具
系统环境:centos 7
一、安装
(1)yum安装
a、安装epel源
# wget http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
# rpm -ivh epel-release-latest-7.noarch.rpm
# yum repolist ###检查是否已经添加到源列表
b、yum install -y jq
(2)源码安装
a、下载源码包
# wget https://github.com/stedolan/jq/releases/download/jq-1.5/jq-1.5.tar.gz
# tar zxvf jq-1.5.tar.gz
# cd jq-1.5
# ./configure
# make && make install
编译安装完成以后就能在该目录下看见jq二进制文件了,添加到环境变量~/.bashrc
如图:
# source ~/.bashrc
安装完成,现在就可以使用jq命令
二、jq测试
(1)简单测试
# echo '{"yjt":"boy","age":20}' |jq . #注意,命令最后有一个点,代表显示全部的json文件
效果:
注意:jq命令会检查json格式的合法性,如果不合法,将保错,具体的json格式,请浏览:http://www.w3school.com.cn/json/json_syntax.asp 或者 https://stedolan.github.io/jq/manual/
(2)通过key获取值,如何获取呢?
jq '.key'
file文件内容
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
65
66
67
68
69
70
71
|
{ "System_Time" : "2018-11-27 17:42:02" , "Hostname" : "test.com" , "Network" :[ { "Network_Card" : "bond1" , "ip" : "10.126.140.16" , "Input_Traffic" : "4.448K/S" , "Output_Traffic" : "2.649K/S " },{ "Network_Card" : "eth4" , "ip" :null, "Input_Traffic" : "2.679K/S" , "Output_Traffic" : "1.805K/S " },{ "Network_Card" : "eth6" , "ip" :null, "Input_Traffic" : "0.750K/S" , "Output_Traffic" : "0.000K/S " }], "CPU" :{ "us" : "0%" , "sy" : "0%" , "id" : "100%" , "wa" : "0%" , "cpu_rate" : "0.01%" , "CPU_Load_Average" : " 0.15, 0.04, 0.01" , "Running_Process" : "1" , "Total_Process" : "696" , "Host_Running_Time" : " 18 days 22:53" , "User_Connection_Number" : "2" , "CPU_Status" : "Normal" }, "Memory" :{ "total_mem" : "128644M" , "use_mem" : "1373M" , "free_mem" : "127270M" , "use_rate" : "1%" , "free_swap" : "65535M" , "total_swap" : "65535M" , "use_swap" : "0M" , "swap_use_rate" : "0%" , "Memory_Status" : "Normal" , "Swap_Memory_Status" : "Normal" }, "disk" :{ "root_use" : "1%" , "root_status" : "Normal" , "var_use" : "1%" , "vae_status" : "Normal" , "data_use" : "1%" , "data_status" : "Normal" , "data1_use" : "0%" , "data1_status" : "Normal" , "data2_use" : "1%" , "data2_status" : "Normal" , "data3_use" : "1%" , "data3_status" : "Normal" }, "TCP" :{ "TIME_WAIT" : "36" , "FIN_WAIT1" : "0" , "FIN_WAIT2" : "0" , "CLOSE_WAIT" : "0" , "ESTABLISHED" : "2" , "SYN_RECV" : "0" , "LAST_ACKV" : "0" , "CLOSING" : "0" }, "type" : "END" } |
例:
(3)获取不存在的key会返回null
(4)嵌套解析
(5)内建函数
a、has 用来判断是否存在某个key
b、key 用来获取json中的key元素的
例: