Linux之jq
Posted 北漂-boy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux之jq相关的知识,希望对你有一定的参考价值。
什么是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文件内容
{ "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元素的
例:
以上是关于Linux之jq的主要内容,如果未能解决你的问题,请参考以下文章