Parse JSON Values Using Grep


Sometimes you need to quickly find a value in a JSON object from a script or the command line. Using grep allows us to use native functionality (OS dependent) to get the information we need. I prefer to use native functionality as much as possible, without having to install additional tools or dependencies. The common recommendation for parsing JSON from the command line is to use jq, this works but I wanted something simple.

Recently I needed to retrieve a value from my AWS access keys, the response from the AWS CLI looks something like this:

Example JSON File:

"UserName": "Bob",
"Status": "Active",
"CreateDate": "2013-06-04T18:17:34Z",

I needed to get the value for the AccessKeyId. Using grep we can easily get the value with a command like this:

grep -o '"AccessKeyId": "[^"]*' access-keys.json | grep -o '[^"]*$'

Breaking this down:

First we’re using the -o flag, short for --only-matching, which will select only the line that matches the following pattern.

The pattern we define is '"AccessKeyId": "[^"]*' where AccessKeyId is the key that we’re trying to find.

Next, we pass the file to search, e.g. access-keys.json.

Finally we pipe the result into a similar grep -o command to strip away the double-quotes and return just the value.