I would like to use python to parse JSON in batch scripts, for example:
HOSTNAME=$(curl -s "$HOST" | python ?)
Where the JSON output from curl looks like:
'{"hostname":"test","domainname":"example.com"}'
How can I do this with a single line python command?
Based on the JSON below being returned from the curl command ...
'{"hostname":"test","domainname":"example.com"}'
You can then use python to extract the hostname using the python json module:
HOSTNAME=$(curl -s "$HOST" |
python -c \
'import json,sys;print(json.load(sys.stdin)["hostname"])')
Note that I have split the line using a \
to make it more readable on stackoverflow. I've also simplified the command based on chepner's comment.
Original source: Parsing JSON with Unix tools
See also: https://wiki.python.org/moin/Powerful%20Python%20One-Liners