Search code examples
jsonvisual-studio-codejsonlint

How to validate selected text as JSON in VS Code?


Is there an extension or other solution that allows you to validate selected text as JSON in VS Code?

It's something very simple in concept that I've been doing for years in Notepad++, but surprisingly I still haven't found a way to do this in VS Code. The three most popular JSON extensions I installed were not able to do this.

To validate a JSON text block, I currently have to copy the text, then paste it into something like jsonlint.com to validate. There's got to be a better way than this in VS Code.

UPDATE: I'm aware a JSON document is automatically linted in VS Code, but I often work with non-JSON files that have JSON snippets, so it won't work in my situation. Here's an example that caused a real issue on production because of the missing comma that wasn't marked with a red squiggly in VS Code:

[some_template.liquid]

{% schema %}
  {
    ...
    "settings": [
      {
        "type": "header",
        "content": "Content"
      }
      {
        "type": "text",
        "id": "some_id",
        "label": "Some Label"
      }
    ],
    ...
  }
{% endschema %}

Hence, I need a solution that allows me to select a block of text, run a command like "Validate JSON", and have it either auto-correct the selected text, add red squigglies to indicate errors in the JSON, or output a list of errors in the Problems console.


Solution

  • The extension JSON Tools by Erik Lynd allows you to operate on selections.

    Select a piece of code and call the minify or prettify command (there are keybindings defined), it performs a tryParseJSON call and notifies with an info message. If needed you can add a tryParse only command.


    Edit

    I have written the extension JSON Validate that will validate selected text (allows multi selection) and gives you the possibility to move the cursor to the offending line. At max 1 error per selection. If there are no errors the extension is silent (could add a setting to change that).