如何解决使用Sed或awk从curl响应中解析出JSON并分配给变量以供以后使用
我正在编写要在linux设备上运行的bash脚本,因此我无权安装jq,我需要能够使用本机Linux工具
curl --location --request POST "https://api-mp.meraki.com/api/v1/networks/12345/switch/stacks/12345/routing/interfaces" \
--header "X-Cisco-Meraki-API-Key: 123key" \
--header "Content-Type: application/json" \
--data '{
"name": "L3 int","subnet": "192.168.249.0/24","interfaceIp": "192.168.249.2","multicastRouting": "disabled","vlanId": 140,"ospfSettings": {
"area": "0","cost": 1,"isPassiveEnabled": true
}
}' | sed -n 's|.*"interfaceID":"\([^"]*\)".*|\1|p' > $newVar
服务器的响应返回以下内容:
{
"interfaceId": "12345","name": "PA L3 DR Int","ospfSettings": {
"area": "0","isPassiveEnabled": true
}
}
然后,我需要能够在查询字符串参数中访问interfaceID新变量
解决方法
您只是弄错了大小写(ID
中的Id
与interfaceId
)而忘记了:
之后的空格,但是您很接近:
$ sed -n 's|.*"interfaceId": *"\([^"]*\)".*|\1|p' file
12345
使用cat file
代替curl
命令,以显示如何在不知道的情况下将其保存到变量中:
$ var=$(cat file | sed -n 's|.*"interfaceId": *"\([^"]*\)".*|\1|p')
$ echo "$var"
12345
,
能否请您尝试以下。在链接中成功测试 https://ideone.com/EsdCQp
your_command |
awk '
/"interfaceId": "/{
gsub(/[^0-9]+|"\,/,"")
print
}
'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。