How do I extract value of a JSON key using bash shell?
5,031
Your python code works well.
Be aware that you might need brackets around the argument to print
if you use python3
.
echo "$json" | python2 -c 'import json,sys;obj=json.load(sys.stdin);print obj["id"]'
echo "$json" | python3 -c 'import json,sys;obj=json.load(sys.stdin);print(obj["id"])'
Alternatively, use jq
:
echo "$json" | jq -r .id
Output for all solutions above:
abc
Related videos on Youtube
Author by
Dave
Updated on December 18, 2022Comments
-
Dave over 1 year
I'm using bash shell. I would like to include something in my shell script that can extract the value of a certain key in a JSON string ...
davea$ json='{"id": "abc", "name": "dave"}'
I tried "grep", which failed
davea$ grep -Po '"id":.*?[^\\]",' $json usage: grep [-abcDEFGHhIiJLlmnOoqRSsUVvwxZ] [-A num] [-B num] [-C[num]] [-e pattern] [-f file] [--binary-files=value] [--color=when] [--context[=num]] [--directories=action] [--label] [--line-buffered] [--null] [pattern] [file ...]
Then I found a solution involving Python, but this also failed ...
localhost:tmp davea$ echo $json | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["id"]' File "<string>", line 1 import json,sys;obj=json.load(sys.stdin);print obj["id"]
How can I extract the value for the "id" key without installing anything extra on my system?
-
Dave about 4 years@pLumo -- that was the issue, I had Python 3 installed but the code I was using was Python 2.
-
Kusalananda about 4 yearsYour title says you want to use the
bash
shell, but your examples usesgrep
andpython
. Would it be ok to update the title?
-