Bootstrap FreeKB - jq - Append JSON
jq - Append JSON

Updated:   |  jq articles

Let's say you have a file named my.json that contains the following.

{}

 

Here is how you could append a JSON key and value. This will not overwrite my.json, but instead will just store the result in the stdout variable.

~]$ stdout=$(cat my.json | jq '.foo += "bar"'); echo $stdout
{ "foo": "bar" }

 

You can append nested keys.

~]$ stdout=$(cat my.json | jq '.greeting.hello += "world"'); echo $stdout
{ "greeting": { "hello": "world" } }

 

Use double quotes if keys or values contain whitespace.

~]$ stdout=$(cat my.json | jq '.greeting."foo bar" += "hello world"'); echo $stdout
{ "greeting": { "foo bar": "hello world" } }

 

Here is how you could append a list.

~]$ stdout=$(cat my.json | jq '.greeting += ["hello world"]'); echo $stdout
{ "greeting": [ "hello world" ] }

 

Redirection can be used to overwrite my.json with the revised JSON.

stdout=$(cat my.json | jq '.data += ["line two"]'); echo $stdout > my.json

 

You can pipe together multiple statements.

]$ echo {} | jq '.data += [{"foo":"hello"}]' | jq '.data += [{"bar":"world"}]'
{
  "data": [
    {
      "foo": "hello"
    },
    {
      "bar": "world"
    }
  ]
}

 

Or like this.

]$ echo {\"data\":{\"greeting\":[{\"foo\":\"hello\"}]}} | jq '.data.greeting += [{"foo":"world"}]'
{
  "data": {
    "greeting": [
      {
        "foo": "hello"
      },
      {
        "foo": "world"
      }
    ]
  }
}

 

You can escape double quotes so that you can include variables.

~]$ foo=world
~]$ echo {} | jq ".data += [{\"hello\": \"$foo\"}]"
{
  "data": [
    {
      "hello": "world"
    }
  ]
}

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 4a73f4 in the box below so that we can be sure you are a human.