executable
executable

Reputation: 3600

How to get value from json knowing a specifc id in a cURL command

My cURL command returns me some json data like the following :

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

Knowing only the id, how can I return the actions values into a variable ? I know how to parse IDs but how can I get the actions ?

Here is the cURL command :

#!/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 will output all IDS from the json.


Exemple: If I search for id = 1, I will retreive ["power", "reboot"]


I can also retreive actions with :

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

I thought doing something like this :

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

But I have syntax error.

How can I translate this code into a single command line code ?

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

Upvotes: 0

Views: 2030

Answers (2)

AlexanderESmith
AlexanderESmith

Reputation: 194

From CLI, you could use jq;

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

In your case, it would probably be something like (not tested) :

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

More information/examples for jq;

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

Upvotes: 0

Albin Paul
Albin Paul

Reputation: 3419

Generally the norm is to not use exec in python but since you wanted to be in one line, here you go

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

While saying this I suggest just creating another python file and let this job be done by that file , Hope it helps :)

Upvotes: 1

Related Questions