【发布时间】:2019-02-06 14:15:29
【问题描述】:
我的 cURL 命令返回一些 json 数据,如下所示:
{
"all":[
{
"id":"1",
"actions":[
"power",
"reboot"
]
},
{
"id":"2",
"actions":[
"shutdown"
]
},
{
"id":"3",
"actions":[
"backup"
]
}
]
}
只知道id,如何将actions 值返回到变量中?我知道如何解析 ID,但如何获得 actions ?
这是 cURL 命令:
#!/bin/bash
IDS=$(curl https://DOMAIN/API -H "X-Auth-Token: $TOKEN" | python -c "import sys, json; print [i['id'] for i in json.load(sys.stdin)['all']]")
$IDS 将从 json 中输出所有 IDS。
示例:
如果我搜索id = 1,我将检索["power", "reboot"]
我还可以使用 :
检索操作#!/bin/bash
ACTIONS=$(curl -s https://DOMAIN/API -H "X-Auth-Token: TOKEN" | python -c "import sys, json, re; print [ i['allowed_actions'] for i in json.load(sys.stdin)['servers']]")
我想这样做:
#!/bin/bash
ACTIONS=$(curl -s https://DOMAIN/API -H "X-Auth-Token: TOKEN" | python -c "import sys, json, re; print [ if i['id'] == '1': i['allowed_actions'] for i in json.load(sys.stdin)['servers']]")
但是我有语法错误。
如何将此代码转换为单个命令行代码?
for i in json.load(sys.stdin)['all']:
if i['id'] == '1':
print(i['actions'])
【问题讨论】:
-
如果你想在bash中读取
json文件,考虑使用jq而不是调用python。 -
是的,我知道,但我不想安装第三方