Using Sed to Parse JSON - R&D Solutions

Using Sed to Parse JSON

Sed is the ultimate stream editor.

I’ve been using it for various text manipulation tasks. In one of my projects I was building a Continuous Delivery Pipeline using  Thoughtworks GO sever. The app I was deploying had a configuration file in JSON format and here’s where sed came in to play.

A common technique when building Continuous Delivery is to build once and deploy to many environments, e.g. DEV, Staging and Production. I had to figure out how to change/transform key values of the config.json file to accommodate a particular environment needs during deployment. If you have dealt with web.config transformation in ASP.NET, you probably know what type of functionality I was missing in my case.

The syntax I came up with was:

sed -i "/\"dbPass\":/ c\ \"dbPass:\" ${dbPass},"  /var/go/deploy/config.json

The above command’s meaning is: open config.json file and replace every line that contain “dbPass” with “dbPass\”:  ${dbPass} parameter then save the file.

Here is a simplified version of the JSON format file that the command should act upon successfully:

{

  "dbUser" : ""

}
If you are wondering what ${dbUser} code means, it is a code block that reads Thoughtworks Go server environment variable from the pipeline.

Talk to us now

Contact us