Working with GeoJSON 🗺️ and VS Code

Carl Saunders - Apr 20 '20 - - Dev Community

I've been working on a project that uses GeoJSON to display geographical points on a interactive map. Whilst working with the .geojson files I noticed that VS Code was not validating the JSON or providing the usual IntelliSense when typing.

GeoJSON is a format for encoding a variety of geographic data structures.

- https://geojson.org/

This is because VS Code does not know how to validate the JSON and the JSON Schema for this file extension has not been registered.

So how do we fix this? The below steps can be used to configure VS Code with any JSON Schema for a file extension.

Add the JSON Schema

First we need to open VS Code, once you've opened VS Code we need to edit the settings.json file. To open the Settings editor use the following VS Code menu command:

  • On Windows/Linux - File > Preferences > Settings
  • On macOS - Code > Preferences > Settings
Note: You can also open the Settings editor from the Command Palette (Ctrl+Shift+P) with Preferences: Open Settings or use the keyboard shortcut (Ctrl+, for Windows and ⌘+, for macOS).

In the Settings editor type JSON: Schemas and click the link Edit in settings.json in the filtered results panel.

Using the above approach will open the Settings editor with the "json.schemas" array expanded. Now all we have to do is insert the correct JSON Schema as an entry within this array.

The first thing we need to do is setup the file extension VS Code will used to validate. As the common file extension for GeoJSON is .geojson, we can use a fileMatch property (which expects an array of file extensions) with the value of ["*.geojson"]. The next property is the url, which indicates where the JSON Schema is located. VS Code will download this file and then validate the JSON against this schema.

Luckily for us GeoJSON is a standard and it already has a defined JSON Schema and can be found at the following URL:

So the final JSON for defining the GeoJSON JSON Schema will look something like the below.

"json.schemas": [
    {
      "fileMatch": [
        ".geojson"
      ],
      "url": "http://json.schemastore.org/geojson"
    }
  ]
Enter fullscreen mode Exit fullscreen mode

Save the file and your GeoJSON will now be validate using the JSON Schema specified.

Invalid GeoJSON validated via JSON Schema

Invalid GeoJSON validated via JSON Schema in VS Code

If you visit http://schemastore.org you will notice many more JSON Schemas, so if you find VS Code does not support a JSON file your using regularly then you can use the above steps to add support along with the JSON Schema from the http://schemastore.org or your own.

Resources

. . . . . . . . . . . . . . . . .