Ryan
Ryan

Reputation: 433

declaring bash variable from parsing JSON with curl and python

I have a URL endpoint that I want to retrieve a value from a JSON array. If I use the following in a linux command line, it works perfectly:

curl -s http://10.10.1.10/api/ping | python -c 'import sys, json; print json.load(sys.stdin)["service"]'

Where "service" is the member I'm trying to access. I get a valid output such as Collection Service I want to assign this output to a variable in a bash script.

#!/bin/bash
SERVICE= "$(curl -s http://10.10.1.10/api/ping)" | python -c 'import sys, json; print json.load(sys.stdin)["service"]'

However, this just gives me an error, saying that my JSON array is not a command.

Is this possible? What am I doing wrong?

Upvotes: 0

Views: 1466

Answers (2)

Eric Renouf
Eric Renouf

Reputation: 14510

You have some odd quoting and bracing in your example. I think if you just take the command that works to print the value you want and put it in $(...) you'll get what you want, so it would be like

SERVICE=$(curl -s http://10.10.1.10/api/ping | python -c 'import sys, json; print json.load(sys.stdin)["service"]')

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1122322

You can use ` backticks to capture a value from a command:

SERVICE=`curl -s http://10.10.1.10/api/ping | python -c 'import sys, json; print json.load(sys.stdin)["service"]'`

or put the $(...) around the whole command; `...` and $(...) are equivalent here:

SERVICE=$(curl -s http://10.10.1.10/api/ping | python -c 'import sys, json; print json.load(sys.stdin)["service"]')

Upvotes: 4

Related Questions