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
Top comments (1)
Nice work!
Carol Skelly
carolskelly https://codeply.com