Json

JSON:為值匹配模式提取並列印鍵和值對

  • October 9, 2022

JSON:

"{
 "a": "https://is2-ssl.com/",
 "b": "https://a5.-ssl.com/",
 "type": "response",
 "c": [
   {
     "Number": 1,
     "Reportname": "XXX",
     "size": "2.5",
     "Variants": [
       "YYY"
     ]
   }
 ],
"Meta": "ABC"
}

所需輸出:

XXX,a,https://is2-ssl.com/
XXX,b,https://a5.-ssl.com/

我想列印那些值包含“http”(url)的鍵值對,並將鍵和值與分隔符“,”合併,並將 ReportName 添加到它們

假設"JSON 文件中的初始值是一個錯字,您希望數組中第一個條目中的.ReportName鍵值,並且您希望輸出為 CSV:c

$ jq -r '.c[0].Reportname as $n | map_values(select(type == "string" and startswith("http"))) | to_entries[] | [$n, .key, .value] | @csv' file
"XXX","a","https://is2-ssl.com/"
"XXX","b","https://a5.-ssl.com/"

jq表達式:

.c[0].Reportname as $n |
map_values(select(type == "string" and startswith("http"))) |
to_entries[] | [$n, .key, .value] | @csv

這首先挑選出.Reportname值並將其分配給內部jq變數$n。然後它通過丟棄與以 substring 開頭的字元串無關的任何鍵來重寫原始對象http

範例文件在map_values()縮減為

{
 "a": "https://is2-ssl.com/",
 "b": "https://a5.-ssl.com/"
}

然後將其轉換to_entries為等價於

[
  { "key": "a", "value": "https://is2-ssl.com/" },
  { "key": "b", "value": "https://a5.-ssl.com/" }
]

…自己訪問密鑰。

該數組被擴展為一組對象,[]其中保存的值與該組中每個對象的一部分$n一起用於創建一個數組,該數組被轉換為引用的 CSV 輸出。.key``.value``@csv


另一個jq具有相同輸出的表達式,但它執行得更to_entries早一些,然後map()在創建的數組上執行,而不是像我們在map_values()上面所做的那樣在對象的值上執行。

.c[0].Reportname as $n | 
to_entries | 
map(
  select(.value | type == "string" and startswith("http")) |
  [$n, .key, .value] | @csv
)[]

引用自:https://unix.stackexchange.com/questions/720368