之前了解Lua中如何解析Json字符串,现在了解一下shell中如何解析Json字符串, 常用到的方法使用正则表达式配合grep/awk/sed来进行解析, 这样解析起来比较麻烦, 前辈们考虑的很全面,shell中有没有命令可以解析呢? 当然是有的,那就是jq
jq Description
A jq program is a “filter”: it takes an input, and produces an output. There are a lot of builtin filters for extracting a particular field of an object, or converting a number to a string, or various other standard tasks.
jq程序是一个"过滤器", 它有一个输入, 并产生一个输出. 有很多内置的过滤器由于提取对象中的特定字符串,或将数字转换为一个字符串或其他标准任务
Linux 安装
官网说的非常详细
- 源码安装
- jq 安装到mipsel平台,参见 README可知 --host 指定编译器
- ./configure --host mipsel-linux
- make
- jq 拷贝到mipsel平台测试成功(前提是必须安装mipsel-linux-gcc编译器)
- 查看系统环境变量, echo $[PATH, 拷贝到指定位置
通过源码安装jq
Json Parse
-
通过jq . 能够将json字符串很好的排列
-
如何获取"employees"数组中第一个name字段的数据
#!/bin/bash
//-r 代表过滤掉字符串的双引号
var=`cat test.txt | jq -r '.employess[0].name'`
echo "$var"