Search code examples
jsonvisual-studio-code

How can I validate JSON in VS Code using a schema file defined in the workspace?


I have followed the instructions in the VS Code documentation under Editing JSON with Visual Studio Code in section Mapping to a schema in the workspace. I created a folder in the workspace root called json-schema and put a file called device_plugin_data_schema.json in it. Then I added the following to my settings.json:

    "json.schemas": [
        {
            "fileMatch": [
                "plugin*.json"
            ],
            "url": "./json-schema/device_plugin_data_schema.json"
        }
    ],

When I open a file that should be validated with that schema, I get the following error:

Unable to load schema from '\.\json-schema\device_plugin_data_schema.json': ENOENT: no such file or directory, open 'c:\json-schema\device_plugin_data_schema.json'.

It is supposed to use relative path but it is not?!

I am using VS Code Version: 1.81.0


Solution

  • If you want to use a relative path to something in a workspace folder for the url property of a JSON schema setting item, you need to define that setting in the workspace settings (<workspace-folder-path>/.vscode/settings.json) instead of in the user settings. Related docs are here.

    If you insist to define it in the user settings.json, I think you need to use an absolute path.

    I think this is a sensible design. User settings apply to all workspaces, so if if relative paths were supported there, it would be an assumption that every single folder you open as a workspace would have a schema file that you'd want to use at such a path (presumably relative to the workspace folder, which I think would be a rather poor assumption, or lead to surprising users (in a bad way)).

    Also note that if you want to specify schema files on a per-JSON-file-basis, you can use the $schema property in the JSON file you want to be validated to specify the schema to use.