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
Share:
5,031

Related videos on Youtube

Dave
Author by

Dave

Updated on December 18, 2022

Comments

  • Dave
    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
      Dave about 4 years
      @pLumo -- that was the issue, I had Python 3 installed but the code I was using was Python 2.
    • Kusalananda
      Kusalananda about 4 years
      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?