Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将此代码写入单行命令_Python_Json_Python 2.7_Shell - Fatal编程技术网

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

Python 如何将此代码写入单行命令,python,json,python-2.7,shell,Python,Json,Python 2.7,Shell,我有一个curl命令,它返回一些json结果 { "all":[ { "id":"1", "actions":[ "power", "reboot" ] }, { "id":"2", "actions":[ "shutdown" ] }, { "id"

我有一个curl命令,它返回一些json结果

{  
    "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
文件“”,第1行
导入sys、json、re;对于json.load(sys.stdin)中的i['all']:\n如果i['id']='1':\n打印(i['actions'])
^
SyntaxError:无效语法

要打印此表达式:

[i['actions'] for i in json.load(sys.stdin)['all'] if i['id'] == '1']
这将过滤
id==1的子字典,并使用
操作
数据构建一个列表

因此适用于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似乎是唯一的,因此最好避免返回单元素列表:

next((i['actions'] for i in json.load(sys.stdin)['all'] if i['id'] == '1'),None)
使用该表达式,它会产生
['power','reboot']
None
,如果找不到,请尝试一下。它是一个轻量级且灵活的命令行JSON解析器,是Ubuntu(
apt install jq
)和Red Hat(
yum install jq
)中的标准包

它可以与JSON和标准UNIX工具一起使用。如果要将输出馈送到常规工具,请使用
-r

$ curl ... | jq -r '.all[] | select(.id=="1").actions[]' 
power
reboot

我想避免使用第三方
$ curl ... | jq -r '.all[] | select(.id=="1").actions[]' 
power
reboot