Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

json

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?

like image 774
Chris Snow Avatar asked Jul 20 '16 17:07

Chris Snow


People also ask

How do I parse a JSON in Python?

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.

How do I extract text from a JSON file in Python?

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.

How do I read a JSON string in Python?

If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.

How does Python fetch JSON data?

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.


1 Answers

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

like image 143
Chris Snow Avatar answered Sep 27 '22 23:09

Chris Snow