我cURL命令返回我喜欢下面的一些JSON数据:
{
"all":[
{
"id":"1",
"actions":[
"power",
"reboot"
]
},
{
"id":"2",
"actions":[
"shutdown"
]
},
{
"id":"3",
"actions":[
"backup"
]
}
]
}
只知道id
,我怎么能返回actions
值到一个变量?我知道如何解析的ID,但我怎么能得到actions
?
这里是卷曲的命令:
#!/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。
例:如果我要寻找的qazxsw POI,我会检索qazxsw POI
我还可以retreive用行动:
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']]")
一般来说,规范是不使用EXEC在Python但因为你想在一个行,在这里你走
#!/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']]")
虽然说这个我建议只是创造另一个Python文件,并让这项工作由文件来完成,希望它能帮助:)
从for i in json.load(sys.stdin)['all']:
if i['id'] == '1':
print(i['actions'])
,你可以使用cat temp | python -c "exec(\"import sys,json \nfor i in json.load(sys.stdin)['all']:\n if i['id'] == '1':\n print(i['actions'])\")"
;
CLI
在你的情况下,它可能会是这样的(未测试):
jq
更多信息/对于curl -s "http://api.icndb.com/jokes/random" | jq '.value.joke'
示例;
ACTIONS=$(curl -s "https://DOMAIN/API" | jq '.all.actions')