VSCode dynamic JSON schema validation

Viewed 1482

I have built project for a web application configuration. It includes generated (from TypeScript) JSONSchemas. To simplify - user can configure things like forms - field order (string[]), hidden fields(string[]) etc. JSON Schmeas are very helpful for users, who aren't too familiar with the configuration, and it validates some errors, that could rise from mistakes in the configuration.

But they cannot help in every situation - in those string arrays - user can put any string, and the schema will be valid.

What I would want to make - is some dynamic validation - when the user opens [ for the field order - he has to choose from the list of fields, that would be fetched from the APIs.

Something, like when you type packageName: "" in the package.json dependencies - it gets a version for the given package.

I would think, that I would have to make some VSCode extension for this - but I don't know - where to start. Can someone point me in the direction - an example, where someone uses real time JSON schema validation would be grateful.

1 Answers

Found an answer by digging through vscode source code. Searched all files, that contains package.json and dependencies (regex search (package.json[\s\S\n]*dependencies)|(dependencies[\s\S\n]*package.json)) and found a class PackageJSONContribution and this was exactly what I was looking for.

Then I made a simple extension using yo code (as from the example of Your first extension).

Some interfaces and classes I was unable to import from vscode, I just made a local copies for my extension. Made my own class FooJSONContribution with the only difference - it's getDocumentSelector() function changed to

    public getDocumentSelector(): vscode.DocumentSelector {
        return [{ language: 'json', scheme: '*', pattern: '**/foo.json' }];
    }

Adjusted extensions package.json activationEvents and added "onLanguage:json" (this could be optimised).

Adjusted activate event of the extension by adding

    const contribution = new FooJSONContribution(xhr, true);
    const disposableCompletionItemProvider = vscode.languages.registerCompletionItemProvider(
        contribution.getDocumentSelector(),
        new JSONCompletionItemProvider(contribution),
        '"',
        ':'
    );
    context.subscriptions.push(disposableCompletionItemProvider);

And that's it. All of the foo.json files now work like package.json files -

Things I need to do now - adjust the code of FooJSONContribution.ts to work for my own needs, for my own API's, for my own files.

I Uploaded this example here https://github.com/leqwasd/VsCodeAsyncJsonAutocomplete

Example of foo.json working

Related