Skip to content

Instantly share code, notes, and snippets.

@shadowbrain
Created December 16, 2011 15:32
Show Gist options
  • Save shadowbrain/1486478 to your computer and use it in GitHub Desktop.
Save shadowbrain/1486478 to your computer and use it in GitHub Desktop.
parse json key:value with sed
## Example: Grab the value for the MYSQL_USER key
User=$( sed -n 's/.*"MYSQL_USER": "\(.*\)",/\1/p' /var/lib/credentials.json )
## Example: Grab the value for the MYSQL_PASSWORD key
Passwd=$( sed -n 's/.*"MYSQL_PASSWORD": "\(.*\)",/\1/p' /var/lib/credentials.json )
@ikekim
Copy link

ikekim commented Jun 21, 2018

Really excellent!

@phbernard
Copy link

Note that this regexp does not work when looking for the last field, since it expects a , after the matched value.

As an alternative:

User=$( sed -n 's/.*"MYSQL_USER": "\([^"]*\)"/\1/p' /var/lib/credentials.json )

Note: this one fails if the value contains an escaped " . Regexp-parsing JSON definitely makes you love genuine parsers :)

@akapoor47
Copy link

JSON is stored in variable called - token_response

{ "Code":"Success", "LastUpdated":"2018-12-27T07:16:31Z", "Type":"fakedTypeValue", "AccessKeyId":"fakedAccessKeyIdValue", "Token":"fakedTokenValue" }

When trying to fetch using - echo aws_access_key_id is:$(echo $token_response | sed -n 's/^.*"AccessKeyId":"\([^"]*\)",*$/\1/p')

Following is printed on console without the token value (Seems value for AccessKeyId is not parsed) - aws_access_key_id is:

I wonder what's wrong in my regex above?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment