exe*_*ble 2 python shell json python-2.7
我有一个curl命令返回一些json结果.
{
"all":[
{
"id":"1",
"actions":[
"power",
"reboot"
]
},
{
"id":"2",
"actions":[
"shutdown"
]
},
{
"id":"3",
"actions":[
"backup"
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
我使用此命令检索数据操作:
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']]"
Run Code Online (Sandbox Code Playgroud)
但是我想在命令行的python中使用这段代码:
for i in json.load(sys.stdin)['all']:
if i['id'] == '1':
print(i['actions'])
Run Code Online (Sandbox Code Playgroud)
我试过这个:
curl -s https://DOMAIN/API -H "X-Auth-Token: TOKEN" | python -c "import sys, json, re; print [ if i['id'] == '1': i['actions'] for i in json.load(sys.stdin)['servers']]"
Run Code Online (Sandbox Code Playgroud)
但它返回语法错误
File "<string>", line 1
import sys, json, re; for i in json.load(sys.stdin)['all']:\nif i['id'] == '1':\nprint(i['actions'])
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
你想打印这个表达式:
[i['actions'] for i in json.load(sys.stdin)['all'] if i['id'] == '1']
Run Code Online (Sandbox Code Playgroud)
这将过滤子字典/其中id == 1并使用actions数据构建列表.
所以适应卷曲命令行:
curl -s https://DOMAIN/API -H "X-Auth-Token: TOKEN" | python -c "import sys, json, re; print([i['actions'] for i in json.load(sys.stdin)['all'] if i['id'] == '1'])"
Run Code Online (Sandbox Code Playgroud)
提供简单的python命令行:
[['power', 'reboot']]
Run Code Online (Sandbox Code Playgroud)
id似乎是唯一的,所以也许最好避免返回1元素列表:
next((i['actions'] for i in json.load(sys.stdin)['all'] if i['id'] == '1'),None)
Run Code Online (Sandbox Code Playgroud)
使用该表达式,它会产生['power', 'reboot']或者None如果没有找到
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |