【问题标题】:How to write this code into a one lined command如何将此代码写入单行命令
【发布时间】:2019-06-30 14:20:50
【问题描述】:

我有一个 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

【问题讨论】:

    标签: python json python-2.7 shell


    【解决方案1】:

    你想打印这个表达式:

    [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

    【讨论】:

      【解决方案2】:

      试试jq。它是一个轻量级且灵活的命令行 JSON 解析器,是 Ubuntu (apt install jq) 和 Red Hat (yum install jq) 中的标准包。

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

      它适用于 JSON 和标准 UNIX 工具。如果您想将输出提供给常规工具,请使用 -r:

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

      【讨论】:

      • 我想避免使用第三方
      猜你喜欢
      • 1970-01-01
      • 2012-09-23
      • 2023-03-13
      • 2021-10-09
      • 2020-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      相关资源
      最近更新 更多