executable
executable

Reputation: 3600

How to write this code into a one lined command

I have a curl command which return some json result.

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

I retreive the data actions with this command :

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

But I would like to use this code in python on the command line :

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

I tried this :

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

But it returns a syntax error

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

Upvotes: 2

Views: 109

Answers (2)

John Kugelman
John Kugelman

Reputation: 361849

Give jq a try. It's a lightweight and flexible command-line JSON parser, and it's a standard package in Ubuntu (apt install jq) and Red Hat (yum install jq).

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

It plays nice with both JSON and standard UNIX tools. If you want to feed the output to regular tools use -r:

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

Upvotes: 3

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140256

you want to print this expression:

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

This filters the sub dictionary/ies where id == 1 and builds a list with the actions data.

so adapted to curl command line:

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

Feeding to a simple python command line works:

[['power', 'reboot']]

id seems unique, so maybe it's better to avoid returning a 1-element list:

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

with that expression it yields ['power', 'reboot'] or None if not found

Upvotes: 6

Related Questions