DEV Community

loading...
Codeply

How to make a JSON Linter / Validator with Vue

Carol Skelly
Top girl dev on StackOverflow. Creator of Codeply.com. Love frontend, but full-stack too! #vue #vuetify #bootstrap #css #javascript #react #net
・2 min read

Vue Lint JSON

Here's my latest in a series of helpful snippets I've made on Vue . As a developer, one of my favorite go-to tools is jsonlint.com. I use it so much that I decided to make my own 🙂 JSON Linter using Vue.js.

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 = this.$refs.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)
    }
  }
})

The HTML / Vue Markup

The keep the UI clean and responsive I included Bootstrap 4. This gives you some color classes to make the error and success text contextual.

<div id="app" class="container py-3">
    <div class="row">
        <div class="col-sm-10 mx-auto py-3">
            <h4 class="font-weight-light">JSON Validator / Linter / Formatter with Vue2</h4>
            <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" 
                ref="jsonText" 
                placeholder="paste or type JSON here..."></textarea>
              <pre>{{ prettyFormat }}</pre>
            </div>
        </div>
    </div>
</div>

Voila, check it out for yourself😉 and let me know what you think.

Full source: https://codeply.com/go/932bxkCVow

Discussion (1)

Collapse
tweetfrog profile image
Tom Michew

Nice work!

carolskelly image