0

I have a file in Web development call package.json in this file there is a scripts object with some commands I would like to be able to add automatically some new commands inside "script":{} using jq

BEFORE

{
  "name": "test-project",
  "version": "1.0.0",
  "description": "A Vue.js project",
  "main": "src/main.js",
  "private": true,
  "scripts": {
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
    "start": "npm run dev",
    "unit": "jest --config test/unit/jest.conf.js --coverage",
    "test": "npm run unit",
    "lint": "eslint --ext .js,.vue src test/unit",
    "build": "node build/build.js"
  },
  "dependencies": {
    "vue": "^2.5.2"
  }
}

I want to add

"prettier": "prettier --fix"
"eslint": "eslint run --all"
"foo": "bar"
Shawn
  • 47,241
  • 3
  • 26
  • 60
fedoraname1
  • 531
  • 1
  • 3
  • 8
  • Does this answer your question? [How can I use a file in a command and redirect output to the same file without truncating it?](https://stackoverflow.com/questions/6696842/how-can-i-use-a-file-in-a-command-and-redirect-output-to-the-same-file-without-t) – oguz ismail Jun 19 '22 at 05:18

2 Answers2

2

As bash is tagged, here's a solution using process substitution and heredoc:

jq '.scripts += input' package.json <(cat << EOF
{
  "prettier": "prettier --fix",
  "eslint": "eslint run --all",
  "foo": "bar"
}
EOF
)
{
  "name": "test-project",
  "version": "1.0.0",
  "description": "A Vue.js project",
  "main": "src/main.js",
  "private": true,
  "scripts": {
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
    "start": "npm run dev",
    "unit": "jest --config test/unit/jest.conf.js --coverage",
    "test": "npm run unit",
    "lint": "eslint --ext .js,.vue src test/unit",
    "build": "node build/build.js",
    "prettier": "prettier --fix",
    "eslint": "eslint run --all",
    "foo": "bar"
  },
  "dependencies": {
    "vue": "^2.5.2"
  }
}
pmf
  • 24,478
  • 2
  • 22
  • 31
1

As jq does not have in-place editing, you need to use a temporary file to update package.json:

tmp="$(mktemp)"
jq '.scripts += {
  "prettier": "prettier --fix",
  "eslint": "eslint run --all",
  "foo": "bar"
}' package.json > "$tmp" && mv "$tmp" package.json
Philippe
  • 20,025
  • 2
  • 23
  • 32