Bash (Scripting) - Parse JSON (python)

by
Jeremy Canfield |
Updated: January 04 2022
| Bash (Scripting) articles
Bash (and Linux systems) do not have a command that is used to parse JSON. For this reason, some other programming language, such as Perl or Python can be used to parse JSON. For example, let's say foo.json contains the following.
{
"id": {
"username": "john.doe",
"password": "itsasecret"
},
Here is how you could parse foo.json using Python. This assumes that Python is installed and running on your Linux system.
cat foo.json | python -c "import sys, json; print(json.load(sys.stdin)['id']['username'])"
Which should return the value.
john.doe
And the return code should be 0 (successful).
~]# echo $?
0
On the other hand, let's say the JSON file does NOT contain the "username" key. In this scenario, something like this should be returned.
Traceback (most recent call last):
File "<string>", line 1, in <module>
KeyError: 'username'
And the return code should be 1 (failed).
~]# echo $?
1
Did you find this article helpful?
If so, consider buying me a coffee over at