How to Replace Variable Value in JSON or YAML File?

PowerADM.com / Linux / How to Replace Variable Value in JSON or YAML File?

Some administrators use sed or regular expressions to replace variable values in structured files (JSON or YAML). This doesn’t always give a good result. It is much easier to use the jq or yq tools to process structured files.

You can use jq to process JSON files. Install jq in Ubuntu:

$ sudo apt update
$ sudo apt install -y jq

Replace variable in JSON or YAML file

Check the version:

$ jq --version

To change the value of a variable in a JSON file, run the command:

$ jq '.grocery.fruits= "banana "' file.json

In this example, we have set a new value for the .grocery.fruits variable.

You can update the value in the JSON file using a variable:

variable="apple"; jq --arg variable "$variable" '.foo.bar = $variable' file.json

For YAML files, you need to use the yq utility. To install this tool:

$ sudo wget -qO /usr/local/bin/yq https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64
$ sudo chmod a+x /usr/local/bin/yq
$ yq --version

In order to change the value of a variable in a YAML file, run the command:

$ yq -i '.grocery.fruits=orange' file.yaml
Leave a Reply

Your email address will not be published. Required fields are marked *