Assuming your JSON document looks something like
{
"scripts": {
"other-key": "some value"
}
}
... and you'd like to insert some other key-value pair into the .scripts object. Then you may use jq to do this:
$ jq '.scripts.watch |= "tsc -w"' file.json
{
"scripts": {
"other-key": "some value",
"watch": "tsc -w"
}
}
or,
$ jq '.scripts += { watch: "tsc -w" }' file.json
{
"scripts": {
"other-key": "some value",
"watch": "tsc -w"
}
}
Both of these would replace an already existing .scripts.watch entry.
Note that the order of the key-value pairs within .scripts is not important (as it's not an array).
Redirect the output to a new file if you want to save it.
To add multiple key-value pairs to the same object:
$ jq '.scripts += { watch: "tsc -w", dev: "nodemon dist/index.js" }' file.json
{
"scripts": {
"other-key": "some value",
"watch": "tsc -w",
"dev": "nodemon dist/index.js"
}
}
In combination with jo to create the JSON that needs to be added to the .scripts object:
$ jq --argjson new "$( jo watch='tsc -w' dev='nodemon dist/index.js' )" '.scripts += $new' file.json
{
"scripts": {
"other-key": "some value",
"watch": "tsc -w",
"dev": "nodemon dist/index.js"
}
}
sed is good for parsing line-oriented text. JSON does not come in newline-delimited records, and sed does not know about the quoting and character encoding rules etc. of JSON. To properly parse and modify a structured data set like this (or XML, or YAML, or even CSV under some circumstances), you should use a proper parser.
As an added benefit of using jq in this instance, you get a bit of code that is easily modified to suit your needs, and that is equally easy to modify to support a change in the input data structure.
sedis the wrong tool for working with JSON. Something likejqwould be better. It looks as if you want to insert a key-value pair in some JSON object. Where is thescriptskey located within the JSON document? – Kusalananda Dec 23 '20 at 08:55scriptskey is located in the first level of thejsonfile. It ispackage.jsonshipped withnpm init -y. is usingsednot feasible in this case? – PHD Dec 23 '20 at 08:58