Home > front end >  Jq how update an object in json
Jq how update an object in json

Time:06-19

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"

CodePudding user response:

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"
  }
}

CodePudding user response:

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
  • Related