Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jq add fields into json

I have the following json :

{
  "databases": [
    {
      "dbsid": "DB1",
      "login": "db1_user",
      "password": "fooXXXbar"
    },
    {
      "dbsid": "db2",
      "login": "alex",
      "password": "bar123foo"
    }
  ]
}

Now, I’d like to add a new record.
I’ve tried something like :

jq '.databases += {"password": "toto", "login":"bla", "dbsid":"foo"}' < file.json

But it outputs an error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

parse error: Objects must consist of key:value pairs at line 13, column 1
exit status 4

Could you please show me the right syntax ?
Regards

>Solution :

First, close the array with a closing square bracket ] between the last two object-closing curly braces:

    }
  ]
}

Then, also wrap the item to be added in array brackets, as you can only add arrays with +:

jq '.databases += [{"password": "toto", "login":"bla", "dbsid":"foo"}]' < file.json
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading