skip to Main Content

I am trying to use the npm package.json to edit the VS Code settings from a bash script. I found How to change VS Code settings from terminal (bash) which has helped me to almost achieve what I wanted.

I am trying to change the color theme of the workbench. My settings.json currently looks like this and is located under HOME/.config/Code/User/ (Linux):

{
   "workbench.colorTheme": "Default Dark Modern"
}

My bash script looks as follows:

#! /usr/bin/bash

json -I -f $HOME/.config/Code/User/settings.json -e 'this.workbench.colorTheme="Default Dark Modern"'

and I get the following error:

undefined:3
this.workbench.colorTheme="Default Dark Modern"
                         ^

TypeError: Cannot set properties of undefined (setting 'colorTheme')
    at Object.eval (eval at main (/usr/lib/node_modules/json/lib/json.js:1365:27), <anonymous>:3:26)
    at parseChunk (/usr/lib/node_modules/json/lib/json.js:1569:29)
    at /usr/lib/node_modules/json/lib/json.js:1426:13
    at getInput (/usr/lib/node_modules/json/lib/json.js:738:17)
    at main (/usr/lib/node_modules/json/lib/json.js:1396:9)
    at Object.<anonymous> (/usr/lib/node_modules/json/lib/json.js:1764:5)
    at Module._compile (node:internal/modules/cjs/loader:1368:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1426:10)
    at Module.load (node:internal/modules/cjs/loader:1205:32)
    at Module._load (node:internal/modules/cjs/loader:1021:12)

Node.js v21.7.1

I think it has something to do with that the key "workbench.colorTheme" is separated by a dot, but I unfortunately cannot find anything to fix this issue. I have already tried switching out the " " with ‘ ‘ and accessing the key in different ways, for example this[workbench.colorTheme] or this.workbench[colorTheme]

2

Answers


  1. I’m not familiar with the json NPM package, but jq is much more common tool that is purpose-built for command-line JSON manipulation.
    If you want to edit this JSON inline, then you want to pipe the jq result to sponge

    Example:

    jq '.["workbench.colorTheme"] |= "My New Theme"' /tmp/foo.json | sponge /tmp/foo.json
    

    For Example:

    $ cat /tmp/foo.json
    {
      "workbench.colorTheme": "Default Dark Modern"
    }
    $ jq '.["workbench.colorTheme"] |= "My New Theme"' /tmp/foo.json | sponge /tmp/foo.json
    $ cat /tmp/foo.json
    {
      "workbench.colorTheme": "My New Theme"
    }
    
    Login or Signup to reply.
  2. The brackets and quotes are needed.

    #!/usr/bin/env bash
    
    json -I -f $HOME/.config/Code/User/settings.json -e 'this["workbench.colorTheme"]="Default Dark Modern"'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search