linux下的json解析工具jq的使用笔记
如何使用強大的命令行json解析工具jq
一、json的基礎知識
1.json是什么
定義:json是一種通用的數(shù)據(jù)交換格式,其本質(zhì)是javascript中的對象和數(shù)組,所以這兩種結構就是對象和數(shù)組兩種結構,json被廣泛應用于數(shù)據(jù)交換中。(如前后端數(shù)據(jù)交換)
形式:數(shù)組,對象
通過這兩種結構可以表示各種復雜的結構
1、對象:對象在js中表示為“{}”括起來的內(nèi)容,數(shù)據(jù)結構為 {key:value,key:value,…}的鍵值對的結構,在面向?qū)ο蟮恼Z言中,key為對象的屬性,value為對應的屬性值,所以很容易理解,取值方法為對象.key 獲取屬性值,這個屬性值的類型可以是數(shù)字、字符串、數(shù)組、對象幾種。
2、數(shù)組:數(shù)組在js中是中括號“[]”括起來的內(nèi)容,數(shù)據(jù)結構為 [“java”,“javascript”,“vb”,“c++”…],取值方式和所有語言中一樣,使用索引獲取(從0開始),字段值的類型可以是數(shù)字、字符串、數(shù)組、對象幾種。
例如:我們往一個url發(fā)送GET請求,返回多個json對象,這些json對象組合成一個json對象數(shù)組。
json對象(格式化形式)
json對象數(shù)組(格式化形式)
[{"id":1,"name":"zhangsan","age":24,"desc":"無名俠客","company":["baidu","google","alibaba"]},{"id":2,"name":"lisi","age":18,"desc":"勇往直前","company":["tencent","google","bytedance"]} ]壓縮的形式:(實際傳輸?shù)臅r候是壓縮形式)
{"id":1,"name":"zhangsan","age":24,"desc":"無名俠客","company":["baidu","google","alibaba"]}總結:
json對象是以{}包括起來的無序的鍵值對集合,數(shù)組是有序的值集合。(這里的值可以是數(shù)字,字符串,json對象,數(shù)組)
2.json序列化和反序列化
序列化:字典 / 列表 / 數(shù)字 /對象 -經(jīng)過序列化 —>字符串 (從面向?qū)ο蟮慕嵌葋碚f,序列化就是把對象轉(zhuǎn)換成json格式的字符串)
反序列化:字符串 —> 字典 / 列表 / 數(shù)字 /對象 (反序列化就是把json字符串變回對象) 為什么要序列化
- 要把內(nèi)容寫入文件
- 網(wǎng)絡傳輸數(shù)據(jù) 序列化
參考文檔:json語法
二、如何在命令行使用jq工具
背景:一般情況下我們可以有很多辦法處理返回回來的json數(shù)據(jù),使其以我們想要格式顯示,在集成開發(fā)環(huán)境中可以用各種類庫來實現(xiàn),而在linux中可以通過awk語法對json數(shù)據(jù)進行處理,更為便捷的辦法就是采用jq工具。
1.如何下載jq工具
ubuntu系統(tǒng)下:
apt install jqlinux系統(tǒng)下
yum install jq下載失敗的幾種原因:
- 沒有在root用戶權限下下載
- 沒有配置鏡像源
2.jq表達式
①什么是jq表達式
- jq表達式實際上就是過濾器,過濾出我們想要的數(shù)據(jù)格式。
- jq 表達式支持串行化操作。一個復雜的表達式可以有多個簡單的,以"|"符號分割的,串行化執(zhí)行的表達式組成。每個表達式以其前邊表達式的結果為輸入。例如:有 JSON 數(shù)據(jù){“name”:{“firstname”:“Tom”,“l(fā)astname”:“Clancy”}}。我們要查詢 lastname 屬性可以使用表達式’.name|.lastname’。
②基礎表達式
基礎表達式(Basic filters)是 jq 提供的基本過濾器,用來訪問 JSON 對象中的屬性。基礎表達式也是實現(xiàn)更復雜查詢功能的基礎。基礎表達式主要有以下幾種:
- ‘.’ 符號。整個JSON對象作為表達式輸入
- 數(shù)組操作,具體見后文
- 表達式操作(‘,‘和 ‘|’)。表達式操作是用來關聯(lián)多個基礎表達式。其中逗號表示對同一個輸入應用多個表達式。管道符表示將前一個表達式的輸出用作后一個表達式的輸入。當前一個表達式產(chǎn)生的結果是迭代器時,會將迭代器中的每一個值用作后一個表達式的輸入從而形成新的表達式。例如’.[]|.+1’, 在這個表達式中, 第一個子表達式'.[]'在輸入數(shù)組上構建迭代器,第二個子表達式則在迭代器的每個元素上加 1。
3.使用jq工具
參考文檔:jq Manual
①查看jq的幫助指令
在命令行輸入jq --help
jq --help jq - commandline JSON processor [version 1.6]Usage: jq [options] <jq filter> [file...]jq [options] --args <jq filter> [strings...]jq [options] --jsonargs <jq filter> [JSON_TEXTS...]jq is a tool for processing JSON inputs, applying the given filter to its JSON text inputs and producing the filter's results as JSON on standard output.The simplest filter is ., which copies jq's input to its output unmodified (except for formatting, but note that IEEE754 is used for number representation internally, with all that that implies).For more advanced filters see the jq(1) manpage ("man jq") and/or https://stedolan.github.io/jqExample:$ echo '{"foo": 0}' | jq .{"foo": 0}Some of the options include:-c compact instead of pretty-printed output;-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;Named arguments are also available as $ARGS.named[], while positional arguments are available as $ARGS.positional[].See the manpage for more options.②常用參數(shù)說明
-s 表示將輸入的多個json對象組合成一個json數(shù)組,也就可以通過索引來操作該JSON數(shù)組了。具體效果如下:
$ cat test.json 現(xiàn)在輸出的是多個json對象 {"id":1,"name":"zhangsan","age":24,"desc":"無名俠客","company":["baidu","google","alibaba"] } {"id":2,"name":"lisi","age":18,"desc":"勇往直前","company":["tencent","google","bytedance"] } $ jq '.[1]'<test.json #無法直接用索引的方式獲取對象 jq: error (at <stdin>:11): Cannot index object with number jq: error (at <stdin>:22): Cannot index object with number$ jq -s '.[1]'<test.json ##加了-s參數(shù),轉(zhuǎn)換成數(shù)組對象,就可以直接用索引的方式獲取對象 {"id": 2,"name": "lisi","age": 18,"desc": "勇往直前","company": ["tencent","google","bytedance"] }-r直接輸出原字符串,而不是JSON文本,也就是把引號去掉。具體如下:
? ~ jq '.[].name' <test.json "zhangsan" "lisi" ? ~ jq -r '.[].name' <test.json zhangsan lisi-S給JSON對象的內(nèi)容按鍵排序
jq -S .<test.json [{"age": 24,"company": ["baidu","google","alibaba"],"desc": "無名俠客","id": 1,"name": "zhangsan"},{"age": 18,"company": ["tencent","google","bytedance"],"desc": "勇往直前","id": 2,"name": "lisi"} ]4.案例分析
①格式化顯示json字符串
用單引號把json數(shù)據(jù)包括起來就是json字符串,如:'json數(shù)據(jù)'
說明:利用管道符的傳遞功能,用jq處理輸出輸入數(shù)據(jù),使其按規(guī)定格式顯示。
格式化顯示全部字符串:
jq .
②如何調(diào)用jq工具
背景:test.json是我們存儲json數(shù)據(jù)的文件。
$ jq . test.json #等價于jq . <test.json [{"id": 1,"name": "zhangsan","age": 24,"desc": "無名俠客","company": ["baidu","google","alibaba"]},{"id": 2,"name": "lisi","age": 18,"desc": "勇往直前","company": ["tencent","google","bytedance"]} ]③數(shù)組操作。
jq 提供三種基礎表達式來操作數(shù)組:
- 迭代器操作(‘.[]’). 該表達式的輸入可以是數(shù)組或者 JSON 對象。輸出的是基于數(shù)組元素或者 JSON 對象屬性值的 iterator。
- 訪問特定元素的操作(‘.[index]‘或’.[attributename]’)。用來訪問數(shù)組元素或者 JSON 對象的屬性值。輸出是單個值
- 數(shù)組切片操作(‘.[startindex:endindex]’),其行為類似于 python 語言中數(shù)組切片操作。
④使用jq串行解析和顯示json中的多個字段
test.json文件
[{"id": 1,"name": "zhangsan","age": 24,"desc": "無名俠客","company": ["baidu","google","alibaba"]},{"id": 2,"name": "lisi","age": 18,"desc": "勇往直前","company": ["tencent","google","bytedance"]} ]現(xiàn)在有test.json文件,我們需要使用jq,連續(xù)顯示名字和年齡,效果如下
zhangsan 24 lisi 18操作:
$ jq '.[] | "\(.name) \(.age)"' <test.json "zhangsan 24" "lisi 18"如何把雙引號去掉呢,加上-r參數(shù)
$ jq -r '.[] | "\(.name) \(.age)"' <test.json zhangsan 24 lisi 18⑤并行顯示多個字段,用,同時使用多個表達式
樣本數(shù)據(jù)
? ~ jq .<test.json [{"id": 1,"name": "zhangsan","age": 24,"desc": "無名俠客","company": ["baidu","google","alibaba"]},{"id": 2,"name": "lisi","age": 18,"desc": "勇往直前","company": ["tencent","google","bytedance"]} ],多個表達式組合的不同效果
? ~ jq '.[0].desc,.[0].name'<test.json "無名俠客" "zhangsan" ? ~ jq '.[0].desc,.[1].name'<test.json "無名俠客" "lisi" ? ~ jq '.[].desc,.[].name'<test.json "無名俠客" "勇往直前" "zhangsan" "lisi"總結
以上是生活随笔為你收集整理的linux下的json解析工具jq的使用笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java如何添加同名的xml节点_jax
- 下一篇: Linux下C语言实现俄罗斯方块——详细