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,則過濾掉
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章