How to use jsonc-parser - 10 common examples

To help you get started, we’ve selected a few jsonc-parser examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DonJayamanne / pythonVSCode / src / client / testing / common / debugLauncher.ts View on Github external
public async readAllDebugConfigs(workspaceFolder: WorkspaceFolder): Promise {
        const filename = path.join(workspaceFolder.uri.fsPath, '.vscode', 'launch.json');
        if (!(await this.fs.fileExists(filename))) {
            return [];
        }
        try {
            const text = await this.fs.readFile(filename);
            const parsed = parse(text, [], { allowTrailingComma: true, disallowComments: false });
            if (!parsed.version || !parsed.configurations || !Array.isArray(parsed.configurations)) {
                throw Error('malformed launch.json');
            }
            // We do not bother ensuring each item is a DebugConfiguration...
            return parsed.configurations;
        } catch (exc) {
            traceError('could not get debug config', exc);
            const appShell = this.serviceContainer.get(IApplicationShell);
            await appShell.showErrorMessage('Could not load unit test config from launch.json');
            return [];
        }
    }
    private resolveWorkspaceFolder(cwd: string): WorkspaceFolder {
github OmniSharp / atom-json-schema / lib / vscode / plugin / jsonFormatter.ts View on Github external
}
    }

    let firstToken = scanNext();
    if (firstToken !== Json.SyntaxKind.EOF) {
        let firstTokenStart = scanner.getTokenOffset() + rangeOffset;
        let initialIndent = repeat(indentValue, initialIndentLevel);
        addEdit(initialIndent, rangeOffset, firstTokenStart);
    }

    while (firstToken !== Json.SyntaxKind.EOF) {
        let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + rangeOffset;
        let secondToken = scanNext();

        let replaceContent = '';
        while (!lineBreak && (secondToken === Json.SyntaxKind.LineCommentTrivia || secondToken === Json.SyntaxKind.BlockCommentTrivia)) {
            // comments on the same line: keep them on the same line, but ignore them otherwise
            let commentTokenStart = scanner.getTokenOffset() + rangeOffset;
            addEdit(' ', firstTokenEnd, commentTokenStart);
            firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + rangeOffset;
            replaceContent = secondToken === Json.SyntaxKind.LineCommentTrivia ? newLineAndIndent() : '';
            secondToken = scanNext();
        }

        if (secondToken === Json.SyntaxKind.CloseBraceToken) {
            if (firstToken !== Json.SyntaxKind.OpenBraceToken) {
                indentLevel--;
                replaceContent = newLineAndIndent();
            }
        } else if (secondToken === Json.SyntaxKind.CloseBracketToken) {
            if (firstToken !== Json.SyntaxKind.OpenBracketToken) {
                indentLevel--;
github imodeljs / imodeljs / tools / certa / src / CertaConfig.ts View on Github external
export function fromConfigFile(filePath: string, overrides: PartialCertaConfig): CertaConfig {
    const fileContents = fs.readFileSync(filePath);
    const fileOpts = parse(fileContents.toString()); // Parsing with jsonc-parser lets us safely handle comments.
    resolvePaths(path.dirname(filePath), fileOpts);
    return fromObject(lodash.defaultsDeep(overrides, fileOpts));
  }
}
github wpilibsuite / vscode-wpilib / vscode / vscode-wpilib / src / cpp / cppgradleproperties.ts View on Github external
// Check which properties changed, and fire new ones
      let current: string | undefined;
      try {
        current = fs.readFileSync(file.fsPath, 'utf8');
      } catch (error) {
      }

      if (current === undefined) {
        this.lastConfig = defaultConfig;
        this.libraryHeaderDirsChanged.fire([]);
        this.localHeaderDirsChanged.fire([]);
        this.propertiesChange.fire();
        return;
      }

      const parsed: IEditorConfig = jsonc.parse(current);
      this.checkForChanges(parsed);
    });
    vscode.workspace.findFiles(this.gradleJsonFileGlob, wp.uri.fsPath).then(async (f) => {
github wpilibsuite / vscode-wpilib / vscode-wpilib / src / cppprovider / apiprovider.ts View on Github external
public async loadConfigs(): Promise {
    this.toolchains = [];

    let file = '';
    try {
      file = await readFileAsync(path.join(this.workspace.uri.fsPath, 'build', this.configFile), 'utf8');
    } catch (err) {
      this.statusBar.show();
      this.binaryTypeStatusBar.show();
      return false;
    }

    this.toolchains = jsonc.parse(file) as IToolChain[];

    if (this.selectedName.Value === 'none') {
      // Look for roborio release first
      const c = this.toolchains[0];
      let name = getToolchainName(c);
      for (const t of this.toolchains) {
        if (t.name === 'linuxathena' && t.buildType === 'release') {
          name = getToolchainName(t);
          break;
        }
      }

      this.selectedName.Value = name;
      this.statusBar.text = this.selectedName.Value;
    }
github wpilibsuite / vscode-wpilib / vscode / vscode-wpilib-cpp / src / cpp_gradle_properties.ts View on Github external
// Check which properties changed, and fire new ones
      let current: string | undefined;
      try {
        current = fs.readFileSync(file.fsPath, 'utf8');
      } catch (error) {
      }

      if (current === undefined) {
        this.lastConfig = defaultConfig;
        this.libraryHeaderDirsChanged.fire([]);
        this.localHeaderDirsChanged.fire([]);
        this.propertiesChange.fire();
        return;
      }

      const parsed: IEditorConfig = jsonc.parse(current);
      this.checkForChanges(parsed);
    });
  }
github microsoft / vscode-cpptools / Extension / src / LanguageServer / colorization.ts View on Github external
public async loadTheme(themePath: string, defaultStyle: ThemeStyle): Promise {
        let rules: TextMateRule[][] = [];
        if (await util.checkFileExists(themePath)) {
            let themeContentText: string = await util.readFileText(themePath);
            let themeContent: any;
            let textMateRules: TextMateRule[];
            if (themePath.endsWith("tmTheme")) {
                themeContent = plist.parse(themeContentText);
                if (themeContent) {
                    textMateRules = themeContent.settings;
                }
            } else {
                themeContent = jsonc.parse(themeContentText);
                if (themeContent) {
                    textMateRules = themeContent.tokenColors;
                    if (themeContent.include) {
                        // parse included theme file
                        let includedThemePath: string = path.join(path.dirname(themePath), themeContent.include);
                        rules = await this.loadTheme(includedThemePath, defaultStyle);
                    }

                    if (themeContent.colors && themeContent.colors["editor.background"]) {
                        this.editorBackground = themeContent.colors["editor.background"];
                    }
                }
            }

            if (textMateRules) {
                // Convert comma delimited scopes into an array
github microsoft / vscode / extensions / extension-editing / src / extensionLinter.ts View on Github external
private readPackageJsonInfo(folder: Uri, tree: JsonNode) {
		const engine = tree && findNodeAtLocation(tree, ['engines', 'vscode']);
		const repo = tree && findNodeAtLocation(tree, ['repository', 'url']);
		const info: PackageJsonInfo = {
			isExtension: !!(engine && engine.type === 'string'),
			hasHttpsRepository: !!(repo && repo.type === 'string' && repo.value && parseUri(repo.value).scheme.toLowerCase() === 'https')
		};
		const str = folder.toString();
		const oldInfo = this.folderToPackageJsonInfo[str];
		if (oldInfo && (oldInfo.isExtension !== info.isExtension || oldInfo.hasHttpsRepository !== info.hasHttpsRepository)) {
			this.packageJsonChanged(folder); // clears this.folderToPackageJsonInfo[str]
		}
		this.folderToPackageJsonInfo[str] = info;
		return info;
	}
github Devine-Davies / vs-make-hidden / src / make-hidden / exclude-items / exclude-items.provider.ts View on Github external
private parseTree(): void  {
        // Get our work space configuration object
        // let fileExcludeObject: any = this.getFilesExcludeObject();
        let fileExcludeObject: any = Util.getItemFromJsonFile(
            this.getSettingPath(), 'files.exclude'
        );

        // FIX
        fileExcludeObject = this.fixRemove__Error( fileExcludeObject );

        if( fileExcludeObject != null ){
            // Update the tree Parse tree accordingly
            this.excludeList = fileExcludeObject;

            this.tree = json.parseTree( JSON.stringify(
                fileExcludeObject
            ) );
        }
    }
github Devine-Davies / vs-make-hidden / src / make-hidden / make-hidden.provider.ts View on Github external
private parse_tree(): void 
    {
        // Get our work space configuration object
        let workspace_config = this.get_workspace_configuration();

        // Parse Tree accordingly
        this.tree =  json.parseTree(
            JSON.stringify( workspace_config )
        );
    }