【问题标题】:How to get value from json knowing a specifc id in a cURL command如何从 json 中获取值,知道 cURL 命令中的特定 id
【发布时间】:2019-02-06 14:15:29
【问题描述】:

我的 cURL 命令返回一些 json 数据,如下所示:

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

只知道id,如何将actions 值返回到变量中?我知道如何解析 ID,但如何获得 actions

这是 cURL 命令:

#!/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。


示例: 如果我搜索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']]")

我想这样做:

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

但是我有语法错误。

如何将此代码转换为单个命令行代码?

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

【问题讨论】:

  • 如果你想在bash中读取json文件,考虑使用jq而不是调用python。
  • 是的,我知道,但我不想安装第三方

标签: python bash shell curl


【解决方案1】:

一般来说,规范是不要在 python 中使用 exec,但既然你想排成一行,那就去吧

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

虽然这么说,但我建议只创建另一个 python 文件并让该文件完成这项工作,希望它有所帮助:)

【讨论】:

    【解决方案2】:

    来自CLI,您可以使用jq

    curl -s "http://api.icndb.com/jokes/random" | jq '.value.joke'
    

    在您的情况下,它可能类似于(未测试):

    ACTIONS=$(curl -s "https://DOMAIN/API" | jq '.all.actions')
    

    jq 的更多信息/示例;

    https://medium.com/cameron-nokes/working-with-json-in-bash-using-jq-13d76d307c4

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-17
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-03
      • 2015-09-16
      相关资源
      最近更新 更多