簡體   English   中英

使用sed和regex從JSON提取數組

[英]Extract array from JSON using sed and regex

我正在嘗試編寫用於調試嵌入式設備的腳本,它們從API檢索JSON對象,該API包含必須運行以調試設備的腳本數組。

{
  "status":"wait",
  "settings":{
    "serialNo": "123456",
    "macAddress":"ff:ff:ff:ff:ff:ff",
    "ipMode": "static|dhcp",
    "ipAddress": "192.168.0.1",
    "ipSubnet": "255.255.255.0",
    "ipGateway": "192.168.0.10",
    "ipDns": "192.168.0.10"
  },
  "scripts":[
    "https://www.google.co.uk/1",
    "https://www.google.co.uk/2",
    "https://www.google.co.uk/3"
  ]
}

當設備運行最少的Linux並通過busybox安裝時,我使用sed來“解析” JSON並從對象中檢索值。 對於單個參數,例如

mac=$(echo $reply | sed -ne 's/^.*"macAddress":"\([^"]*\)".*$/\1/p')
echo $mac
ff:ff:ff:ff:ff:ff

我嘗試使用類似的正則表達式在[]之間匹配數組的內容,但是當我通過sed運行它時,它什么也沒有返回。

scripts=$(echo $reply | sed -ne 's/"scripts":\(\[[^\[\]]*\]\)/\1/p')
echo $scripts

我希望它導致的結果是:

echo $scripts
["https://www.google.co.uk/1","https://www.google.co.uk/2","https://www.google.co.uk/3"]

使用jq您可以發出以下命令:

jq -r '.scripts[]' the.json

如果要將其放入數組,請使用命令替換:

arr=( $(jq -r '.scripts[]'  a.json ) )

現在,您可以使用以下命令訪問各個網址:

echo "${arr[0]}"
echo "${arr[1]}"
echo "${arr[2]}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM