jq 用法

jq 用法

jq是linux or mac下的命令行json解析工具,通常用于本地解析一个比较大的json串,较小的直接json.cn就可以了。

初级用法

jq '.code' xxx.json
jq '.code' "$RESPONSE_JSON"
cat xxx.json | jq '.code'

jq '.data[]' xxx.json 

Comma ,

jq '.code, .message' xxx.json 

Pipeline |

jq '.data | length' xxx.json 

Construction {}

jq '.data[] | {user: .user, device_model: .dm}'

Options

-c               compact instead of pretty-printed output; 非pretty格式,删除无用空格和换行,常用
-n               use `null` as the single input value;
-e               set the exit status code based on the output;
-s               read (slurp) all inputs into an array; apply filter to it;
-r               output raw strings, not JSON texts; 主要针对字符串类型,输出原始字符串,而不是带双引号的
-R               read raw strings, not JSON texts;
-C               colorize JSON;
-M               monochrome (don't colorize JSON);
-S               sort keys of objects on output;
--tab            use tabs for indentation;
--arg a v        set variable $a to value <v>;
--argjson a v    set variable $a to JSON value <v>;
--slurpfile a f  set variable $a to an array of JSON texts read from <f>;
--rawfile a f    set variable $a to a string consisting of the contents of <f>;
--args           remaining arguments are string arguments, not files;
--jsonargs       remaining arguments are JSON arguments, not files;
--               terminates argument processing;

我比较常用的就是-c和-r

高级用法

函数

length 用来计算数组长度,对象size 和 字符串长度
keys 将对象的所有key按数组方式输出,是排好序的
keys_unsorted 将对象的所有key按数组方式输出
has 是否有某个key
in 输入的key是否在某个对象里 jq '.[] | in({"foo": 42})'
map(x), map_values(x) 作用于数组或对象,对容器内的每个元素执行x操作,返回一个新数组 jq 'map(. + 1)'
select(x) 对输入执行谓词x,如果返回true,则输出,若返回false,则过滤掉
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章