Skip to content

Appending JSON

Sometimes you need to add/overwrite key value inside JSON and, bash2json supports that too!

Terminal window
bash2json '{ "foo": "bar" }' --append 'foo1' 'bar1'
# {"foo":"bar","foo1":"bar1"}
Terminal window
bash2json '{ "foo": { "foo1": "bar" } }' --append 'foo.foo2' 'bar1'
# {"foo":{"foo1":"bar","foo2":"bar1"}}

You must include [] to key name to add item to it’s array.

Terminal window
bash2json '{ "foo": [{ "foo1": "bar" }] }' --append 'foo[]' 'bar1'
# {"foo":[{"foo1":"bar"},"bar1"]}

If you want to access object inside array, you have to include [<index>]

Terminal window
bash2json '{ "foo": [{ "foo1": "bar" },{ "foo2" :"bar" }] }' --append 'foo[0].foo' 'bar1'
# {"foo":[{"foo1":"bar","foo":"bar1"},{"foo2":"bar"}]}

Just combine two things from below

Terminal window
bash2json '{ "foo": [{ "foo1": [] },{"foo2": "bar" }] }' --append 'foo[0].foo1[]' 'bar1'
# {"foo":[{"foo1":["bar1"]},{"foo2":"bar"}]}