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?
If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method. If you need to parse a JSON file that returns a dictionary, then you can use the json. load() method.
So first thing you need to import the 'json' module into the file. Then create a simple json object string in python and assign it to a variable. Now we will use the loads() function from 'json' module to load the json data from the variable. We store the json data as a string in python with quotes notation.
If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.
Instead of the JSON loads method, which reads JSON strings, the method used to read JSON data in files is load(). The load() method takes up a file object and returns the JSON data parsed into a Python object. To get the file object from a file path, Python's open() function can be used.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With