Parse json files with comments? (keybindings.json)

119 Views Asked by At

Does VSCode provides any means to parse json files with comments without using external library?

I'm trying get list of keybindings for the extension and need to parse keybindings.json file, which contains comments

I'm currently using JSON5 package, but would like to get rid of it:

//get keybindings
const keybindings = new Promise(resolve => {
  //default keybindings
  const data = require("../package.json").contributes.keybindings.reduce((a,b)=>(a[b.command]=b.key,a),{});
  const parse = list => {
    for(let i = 0; i < list.length; i++) {
      if (list[i].command in data)
        data[list[i].command] = list[i].key;
    }
    for(let i in data) {
      //capitalize first letter
      data[i] = data[i].replace(/\w+/g, w => (w.substring(0,1).toUpperCase()) + w.substring(1));
      //add spaces around "+"
      // data[i] = data[i].replace(/\+/g, " $& ");
    }

    Object.assign(keybindings, data);
    resolve(data);
  };
  const path = {
    windows: process.env.APPDATA + "/Code",
    macos: process.env.HOME + "/Library/Application Support/Code",
    linux: process.env.HOME + "/config/Code"
  }[{
    aix: "linux",
    darwin: "macos",
    freebsd: "linux",
    linux: "linux",
    openbsd: "linux",
    sunos: "linux",
    win32: "windows"
  }[process.platform]||"windows"];
  const file = ((process.env.VSCODE_PORTABLE ? process.env.VSCODE_PORTABLE + "/user-data/User/" : path) + "/User/keybindings.json")
    .replace(/\//g, process.platform == "win32" ? "\\" : "/");

  //read file
  workspace.openTextDocument(file).then(doc => {
    //we can't use JSON.parse() because file may contain comments
    const JSON5 = require("json5").default;
    parse(JSON5.parse(doc.getText()));
  }).catch(er => {
    parse([]);
  });
});
0

There are 0 best solutions below