DEV Community

Cover image for A Vue JSON Linter
Carol Skelly for Codeply

Posted on

A Vue JSON Linter

As a developer, one of my favorite go-to tools is jsonlint.com. I like it so much that I decided to make my own JSON Linter using Vue 2.

The Vue App

This turned out KISS. Just 2 vars for the JSON as a string, and displaying errors. I used a computed prettyFormat method that handle the validation logic.

The prettyFormat method attempts to parse the JSON string, and on error displays the line & position of the problem. To highlight the error position within the JSON, I grab a ref to textarea element, and find the position, and finally use setSelectionRange to highlight the problem text...

const app = new Vue ({
  el: '#app',
  data: {
    jsonstr: "",
    jsonerror: ""
  },
  computed: {
    prettyFormat: function() {
        // reset error
        this.jsonerror = "";
        let jsonValue = "";
        try {
            // try to parse
            jsonValue = JSON.parse(this.jsonstr);
        }
        catch(e) {
            this.jsonerror = JSON.stringify(e.message)
            var textarea = document.getElementById("jsonText");
            if (this.jsonerror.indexOf('position')>-1) {
                // highlight error position
                var positionStr = this.jsonerror.lastIndexOf('position') + 8;
                var posi = parseInt(this.jsonerror.substr(positionStr,this.jsonerror.lastIndexOf('"')))
                if (posi >= 0) {
                    textarea.setSelectionRange(posi,posi+1);
                }
            }
            return "";
        }
        return JSON.stringify(jsonValue, null, 2);
    }
  }
})
Enter fullscreen mode Exit fullscreen mode

The HTML / Vue Markup

The markup is very simple and I used Bootstrap 4 for the styling. As you'll see here there are 2 mutually exclusive divs. The first to show errors, and the 2nd to confirm that the JSON is valid.

The JSON itself is contained in a textarea that's bound to the jsonstr v-model. Finally the <pre> tag displays the formatted JSON...

<div id="vueapp">
   <div class="text-danger" v-if="jsonstr && jsonerror">{{ jsonerror }}</div>
   <div class="text-success" v-if="!jsonerror">Valid JSON ✔</div>
   <textarea v-model="jsonstr" rows="10" class="form-control" id="jsonText" placeholder="paste or type JSON here..."></textarea>
   <pre>{{ prettyFormat }}</pre>
</div>
Enter fullscreen mode Exit fullscreen mode

Grab the code here, and share your comments!😊

Top comments (0)