SHC SHC - 1 year ago 60
JSON Question

how can I parse json with a single line python command?

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:


How can I do this with a single line python command?

Answer Source

Based on the JSON below being returned from the curl command ...


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: