1

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?

4
  • Install jq or json or don't work with JSON data.
    – jesse_b
    Mar 5, 2020 at 15:40
  • 1
    Your python code works well for python2.x, and should work for python3 if you put brackets around the print argument.
    – pLumo
    Mar 5, 2020 at 15:45
  • @pLumo -- that was the issue, I had Python 3 installed but the code I was using was Python 2.
    – Dave
    Mar 5, 2020 at 15:47
  • Your title says you want to use the bash shell, but your examples uses grep and python. Would it be ok to update the title?
    – Kusalananda
    Mar 5, 2020 at 16:31

1 Answer 1

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.