Sed

如何從輸出中提取特定屬性路徑的引用字元串的內容?

  • March 31, 2022

我有一個來自 JSON 格式的 Web 伺服器響應的輸出,如下所示:

{"status":"OK","result":{"string":{"variable":0},"string2":[{"id":"03489579q2074hvissdiuh:023427598042ztuoihsgasflbkc6dc7e000af669d6c94857d1a28f8cb338a9691c80eb8857c750c8ead70f29a","string3":"string4","latitude":"01.XXXXXXXX","longitude":"02.XXXXXXX"},]}}

並保存為response.txt. 它重複了很多次,所以"02.XXXXXXX"}之後","

我的預期輸出只是以下內容"id"

03489579q2074hvidssiuh:023427598042ztuoihsgasflbkc6dc7e000af669d6c94857d1a28f8cb338a9691c80eb8857c750c8ead70f29a

每個 id 後都有一個新行。

我嘗試了諸如

grep -o '".*"' somefile | tr -d '",{}[]'

awk -F- '{
   for (i=1;i<=NF;i++) {
     if ($i ~ "^ram.+") { sub("^ram","",$i); print $i} }
   }' response.txt
id

sed 's/.*id\(\w\+\).*/\1/' response.txt

sed 's/.*id..\(.*\)..300.*/\1/' -d '",{}[]' response.txt

sed 's/^.* id (\([0-9\.%]*\).*$/\1/' response.txt

但它會返回我所有的東西,只有第一次迭代仍然存在一些特殊字元或錯誤,因為預設情況下 macOS 終端中不可用 awk。

謝謝

編輯:這是一個具有更多迭代的輸出

{"status":"OK","result":{"string1":{"veriable":0},"string2":[{"id":"XXXXX:XXXXX","tier":"normal","latitude":"01.XXXXX","longitude":"02.XXXXX"},{"id":"XXXXX:XXXXX","tier":"normal","latitude":"01.XXXXX","longitude":"02.XXXXX"},{"id":"XXXXX:XXXXX,"tier":"special","latitude":"01.XXXXX","longitude":"02.XXXXX"},{"id":"XXXXX:XXXXX","tier":"normal","latitude":"01.XXXXX","longitude":"02.XXXXX"}]}}

使用jq

jq -r '.result.string2[].id' response.txt

輸入:

{
 "status": "OK",
 "result": {
   "string1": {
     "veriable": 0
   },
   "string2": [
     {
       "id": "XXXXX:XXXXX",
       "tier": "normal",
       "latitude": "01.XXXXX",
       "longitude": "02.XXXXX"
     },
     {
       "id": "XXXXX:XXXXX",
       "tier": "normal",
       "latitude": "01.XXXXX",
       "longitude": "02.XXXXX"
     },
     {
       "id": "XXXXX:XXXXX",
       "tier": "special",
       "latitude": "01.XXXXX",
       "longitude": "02.XXXXX"
     },
     {
       "id": "XXXXX:XXXXX",
       "tier": "normal",
       "latitude": "01.XXXXX",
       "longitude": "02.XXXXX"
     }
   ]
 }
}

輸出:

XXXXX:XXXXX
XXXXX:XXXXX
XXXXX:XXXXX
XXXXX:XXXXX

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