27

Hi i am try to show json file result with vue.js the target is that result will be showed on value.

this is my code:

data () {
  return {
    fetchData: function () {

      var self = this;
      self .$http.get( "/api/casetotalactivation", function( data ) {
        self.items = data;
      });
    },

    statsCards: [
      {
        type: 'warning',
        icon: 'ti-server',
        title: 'Cases',
        value: this.items,
        footerText: 'Updated now',
        footerIcon: 'ti-reload'
      }


    ],

7 Answers 7

48

use this code:

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

and JS:

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);
    }
  }
})
Sign up to request clarification or add additional context in comments.

1 Comment

Because my value was a Vue-wrapped object, I actually had to reverse the method order to call JSON.parse after calling JSON.stringify on the value like so: JSON.parse(JSON.stringify(value, null, 2)) Suggested at stackoverflow.com/a/58098164/4531155
36

HTML and JS have this built into the language. Try...

<pre>{{ yourObject }}</pre>

This gives the default indent, to specify a custom indent provide it as the third argument to JSON.stringify(...).

// replace 2 with '\t' to do tab indentation 
<pre>{{ JSON.stringify(yourObject, null, 2) }}</pre>

If you're outside of Vue then using a combo of JSON.stringify and <pre> will work.

2 Comments

great answer! a bit cleaner: <pre>{{ JSON.stringify(yourObject, null, 2) }}</pre>
@AryehBeitz I added to the answers how to specify the indentation :).
26

just use <pre>

<pre>{{json}}</pre>

1 Comment

Best answer, clean and simple
2

Here's one way to display JSON data, using Vue:

  • Display a stringified json object inside a <textarea> using v-model
  • Display object properties with <li v-for="">
<template>
  <div class="hello">
    <textarea v-model="listDataString" rows="20" cols="80"></textarea>
    <ul id="items">
      <li v-for="(item, index) in listData" :key="index">
        {{ `${item.text} [${item.id}]` }}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "RenderList",
  props: {
    msg: String,
  },
  data() {
    return {
      listDataString: String,
      listData: [], // placeholder
    };
  },
  mounted() {
    axios
      .get("=== [API_ENDPOINT] ===")
      .then((response) => {
        this.listDataString = JSON.stringify(response.data, null, "\t");
        this.listData = response.data;
        console.log(this.listDataString);
        return response; // multiline arrow function must return
      });
  },
};
</script>

screenshot

Comments

1

You can also take advantage of computed

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue JSON Output</title>
</head>
<body>

<div id="app">
  <!-- Input to change the name -->
  <div>
    <label for="nameInput">Change Name: </label>
    <input id="nameInput" v-model="myObject.name">
  </div>

  <!-- Display the formatted JSON -->
  <pre>{{ formattedJSON }}</pre>
</div>

<script src="https://unpkg.com/[email protected]/dist/vue.global.js"></script>

<script>
const App = {
  data() {
    return {
      myObject: {
        name: "John",
        age: 30,
        city: "New York"
      }
    };
  },
  computed: {
    formattedJSON() {
      return JSON.stringify(this.myObject, null, 2);
    }
  }
};

Vue.createApp(App).mount("#app");
</script>

</body>
</html>

Comments

0

If the /api is only on the dev server you can create a vue.config.js file in the app root folder.

module.exports = {
  devServer: {
    before: function(app, server) {
      app.get('/api', function(req, res) {
        const result = [{
          type: 'warning',
          icon: 'ti-server',
          title: 'Cases',
          value: this.items,
          footerText: 'Updated now',
          footerIcon: 'ti-reload'}];
        res.writeHead(200, {'Content-Type': 'application/json'});
        res.end(JSON.stringify(result));
      });
    }
  }
}

With this files when I run npm run serve, I get the json object when navigating to /api and my regular app otherwise.

Comments

0

Just use this:

<pre v-html="JSON.stringify(objectJs, null, 2)"></pre>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.