Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode JSON in Bash using python mjson.tool

I need to get a key from JSON in standard bash, and found the following:

echo '{"first_key": "value", "second_key": "value2"}' | python -mjson.tool | grep 'first_key'

But this returns:

"first_key": "value",

How can I just return value, i.e. not the key, and remove the quotes and comma.

Thanks.

like image 361
Justin Avatar asked Jun 29 '13 01:06

Justin


2 Answers

$ echo '{"first_key": "value", "second_key": "value2"}' | python -c 'import sys, json; print(json.load(sys.stdin)[sys.argv[1]])' first_key
value
like image 152
Ignacio Vazquez-Abrams Avatar answered Oct 06 '22 01:10

Ignacio Vazquez-Abrams


Since you tagged it grep here is a solution for that (though Ignacio's solution is the right way to do it):

echo "..." | grep -oP "(?<=\"first_key\": \")[^\"]+"

Output:

$ echo '{"first_key": "value", "second_key": "value2"}' | grep -oP "(?<=\"first_key\": \")[^\"]+"
value
like image 23
jaypal singh Avatar answered Oct 06 '22 03:10

jaypal singh