我正在卷曲一个终点:
#!/bin/bash
instance_info=$(curl -sk https://internal.admin.com/app/instance)
给出了json响应:
{
"basePath": "/install",
"metadata": {
"deployed_artifact": "app01",
"docker": "True",
"http_port": "7471",
"url": "www.google.com"
},
"name": "app-01",
"server": "webserver1"
}
我正在尝试避免使用JQ多次卷曲以从json获取所需的变量。
使用bash我真的很感激,如果有人可以告诉我如何将响应存储为另一个var,然后使用它来变量名称:server:url:http_port:
以下似乎两次卷曲:
#!/bin/bash
instance_info=$(curl -sk https://internal.admin.com/app/instance)
server_name=$(echo instance_info | /usr/bin/jq --raw-output '.server')
url=$(echo instance_info | /usr/bin/jq --raw-output '.url')
答案 0 :(得分:0)
您正在呼叫curl
一次,这就足够了。然后,您将内容包含在变量中,以便无需再次调用curl
即可访问该内容。
关于您的代码,您的方法很好,但在回显变量时您遗漏了$
:
server_name=$(echo $instance_info | /usr/bin/jq --raw-output '.server')
# ^
查看示例。在这里我硬编码JSON:
your_json='
{
"basePath": "/install",
"metadata": {
"deployed_artifact": "app01",
"docker": "True",
"http_port": "7471",
"url": "www.google.com"
},
"name": "app-01",
"server": "webserver1"
}'
代表server
:
$ echo "$your_json" | jq --raw-output '.server'
webserver1
对于url
,您需要指出它所在的块。也就是说,metadata
:
$ echo "$your_json" | jq --raw-output '.metadata.url'
www.google.com
要存储到变量中,请说:
your_field=$(echo "$your_json" | jq --raw-output 'XXXX')
# ^^^^
答案 1 :(得分:0)
alarmManager.set(AlarmManager.RTC_WAKEUP, sdl,
pendingIntent);
O / P:
sed -rn 's/[ ]*"([^"]*)"[^"]*("[^"]*").*/\1=\2/gp'' file.json
basePath="/install"
deployed_artifact="app01"
docker="True"
http_port="7471"
url="www.google.com"
name="app-01"
server="webserver1"
此输出可以获取变量
eval
O / P:
eval $(sed -rn 's/[ ]*"([^"]*)"[^"]*("[^"]*").*/\1=\2/gp' file.json )
echo $name $server
答案 2 :(得分:0)
使用一个jq
传递读取值,然后无需存储json:
read name server url http_port < <(
curl -sk https://internal.admin.com/app/instance | \
jq --raw-output '[.name, .server, .metadata.url, .metadata.http_port] | join(" ")'
)
echo -e "\$name: $name\n\$server: $server\n\$url: $url\n\$http_port $http_port"
$name: app-01
$server: webserver1
$url: www.google.com
$http_port 7471
答案 3 :(得分:0)
这是一个脚本,演示了如何使用jq的SELECT
mt.*,
bd.block_duration
FROM
block_durations bd
left outer JOIN (SELECT * FROM mergetable WHERE acct_id='0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98') mt
ON mt.block_ts = bd.block_ts
格式化指令以及bash @sh
来使用过滤器的输出设置bash变量。在这种情况下,我们硬编码可能来自eval
的json。
curl
运行时会产生输出
#!/bin/bash
instance_info='
{
"basePath": "/install",
"metadata": {
"deployed_artifact": "app01",
"docker": "True",
"http_port": "7471",
"url": "www.google.com"
},
"name": "app-01",
"server": "webserver1"
}'
eval "$(jq -M -r '@sh "server_name=\(.server) url=\(.metadata.url)"' <<< "$instance_info")"
echo $server_name
echo $url
Extract data and set shell variables的JQ Cookbook部分有更多webserver1
www.google.com
的例子。