[英]Extract array from JSON using sed and regex
I'm trying to write a script for comissioning embedded devices, they retrieve a JSON object from an API that contains an array of scripts that must be run to comission the device. 我正在尝试编写用于调试嵌入式设备的脚本,它们从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"
]
}
As the devices run minimal linux installs with busybox I am using sed to "parse" the JSON and retrieve the values from the object. 当设备运行最少的Linux并通过busybox安装时,我使用sed来“解析” JSON并从对象中检索值。 This works fine for single parameters such as 对于单个参数,例如
mac=$(echo $reply | sed -ne 's/^.*"macAddress":"\([^"]*\)".*$/\1/p')
echo $mac
ff:ff:ff:ff:ff:ff
I try to use a similar regex to match the contents of the array between [
and ]
but when I run it through sed it returns with nothing. 我尝试使用类似的正则表达式在[
和]
之间匹配数组的内容,但是当我通过sed运行它时,它什么也没有返回。
scripts=$(echo $reply | sed -ne 's/"scripts":\(\[[^\[\]]*\]\)/\1/p')
echo $scripts
What I would like it to result in is this: 我希望它导致的结果是:
echo $scripts
["https://www.google.co.uk/1","https://www.google.co.uk/2","https://www.google.co.uk/3"]
With jq
you can issue the following command: 使用jq
您可以发出以下命令:
jq -r '.scripts[]' the.json
If you want to put this into an array, use command substitution: 如果要将其放入数组,请使用命令替换:
arr=( $(jq -r '.scripts[]' a.json ) )
Now you can access the individual urls using: 现在,您可以使用以下命令访问各个网址:
echo "${arr[0]}"
echo "${arr[1]}"
echo "${arr[2]}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.