In an attempt to format my JSON string into a highlighted syntax or something similar to JSON prettify using pre element tags. I'm not looking for a tree JSON viewer, just a clean and nice JSON syntax highlight.
Template
<div id="app">
<pre>{{{ json | jsonPretty }}}</pre>
</div>
Vue
var vm = new Vue({
el: '#app',
data() {
return {
json:'{ "name: "John Doe" }'
}
},
filters: {
jsonPretty: function(value) {
let json = JSON.stringify(JSON.parse(value), null, 2)
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+]?\d+)?)/g, function(match) {
var cls = 'number'
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key'
} else {
cls = 'string'
}
} else if (/true|false/.test(match)) {
cls = 'boolean'
} else if (/null/.test(match)) {
cls = 'null'
}
return '<span class="' + cls + '">' + match + '</span>'
})
}
}
});
CSS
pre {
outline: 1px solid #ccc;
padding: 15px;
margin: 5px;
background: white;
}
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
I tested it on JSFiddle and it worked fine but encountered errors when testing with the official VueJS template in Webpack.
ERROR in ./~/vue-loader/lib/template-compiler?{"id":"data-v-4b8ecaca","hasScoped":true,"transformToRequire":{"video":"src","source":"src","img":"src","image":"xlink:href"}}!./~/vue-loader/lib/selector.js?type=template&index=0!./src/components/Hello.vue
(Emitted value instead of an instance of Error)
Error compiling template:
<div class="hello">
<div class="">
<pre>{{{ json | jsonPretty }}}</pre>
</div>
</div>
- invalid expression: {{{ json | jsonPretty }}}
@ ./src/components/Hello.vue 10:2-300
@ ./~/babel-loader/lib!./~/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue
@ ./src/App.vue
@ ./src/main.js
@ multi ./build/dev-client ./src/main.js
Edit: added JSFiddle link