python - 如何将此代码写入单行命令

标签 python json python-2.7 shell

我有一个返回一些 json 结果的 curl 命令。

{  
    "all":[  
    {
        "id":"1",
        "actions":[  
            "power",
            "reboot"
        ]
    },
    {
        "id":"2",
        "actions":[  
            "shutdown"
        ]
    },
    {
        "id":"3",
        "actions":[  
            "backup"
        ]
    }
    ]
} 

我使用此命令检索数据操作:

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']]"

但我想在 python 命令行中使用这段代码:

for i in json.load(sys.stdin)['all']:
    if i['id'] == '1':
        print(i['actions'])

我试过这个:

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']]"

但是返回语法错误

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

最佳答案

你想打印这个表达式:

[i['actions'] for i in json.load(sys.stdin)['all'] if i['id'] == '1']

这会过滤 id == 1 的子字典,并使用 actions 数据构建一个列表。

如此适应于 curl 命令行:

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'])"

输入一个简单的 python 命令行是可行的:

[['power', 'reboot']]

id 似乎是唯一的,所以最好避免返回 1 元素列表:

next((i['actions'] for i in json.load(sys.stdin)['all'] if i['id'] == '1'),None)

使用该表达式它会产生 ['power', 'reboot']None 如果没有找到

关于python - 如何将此代码写入单行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54556871/

相关文章:

java - Spring Boot 。如何将数组转为json

python - 如果我在长度为 1 的 QuerySet 上使用 first() 与 last(),为什么会得到不同的结果

python - 如何从 BeautifulSoup 下载图片?

python - 在 Python 2.x 中创建信息注释的 Pythonic 方式是什么?

javascript - 检测所有 URL 并使它们可点击,并将图像包装在 <img> 标记 JSON 文件中

javascript - 如何在odoo中继承或覆盖js文件?

python - 获取参数名称

python - 更改默认的 auth_user 表名

python - 在 Ubuntu 上使用带有 SpatiaLite 的 GeoDjango 时出错

python - QuerySet 类型的对象不是 JSON 可序列化的 Django