[Vue.js] Pretty Print JSON String


Paste any valid JSON string in the following textarea. You will see the result of pretty print on the fly.

{{ jsonstr | pretty }}

Source Code and Explanation


<div id="vueapp">
  <textarea v-model="jsonstr" rows="8" cols="40"></textarea>
  <pre>{{ jsonstr | pretty }}</pre>

<script src="https://unpkg.com/vue@2.2.4/dist/vue.js"></script>

The idea is simple. We implement a Vue.js filter to pretty print the string in the textarea. According to the answer in [2], the built-in JavaScript JSON.stringify method can help us pretty print the JSON string, so in the filter, JSON.parse the string first and then JSON.stringify it again.


'use strict';

new Vue({
  el: '#vueapp',
  data: {
    jsonstr: '{"id":1,"name":"A green door","price":12.50,"tags":["home","green"]}'
  filters: {
    pretty: function(value) {
      return JSON.stringify(JSON.parse(value), null, 2);

Tested on:

  • Chromium Version 56.0.2924.76 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)
  • Vue.js 2.2.4


[2]How can I pretty-print JSON using JavaScript? - Stack Overflow