Display JSON data using Vue.js

Trying to display JSON file results using Vue.js, with the goal of showing the result in a value.

Here is the code snippet:

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'
      }
    ],

Answer №1

try out this code snippet:

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

also, include the following JavaScript:

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);
    }
  }
})

Answer №2

One of the convenient features in HTML and JS is their built-in capability. Experiment with...

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

The default indent can be obtained by simply using JSON.stringify(...). To specify a custom indent, include it as the third argument.

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

If you are not within Vue, combining JSON.stringify with <pre> will still function effectively.

Answer №3

simply employ the <pre> tag

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

Answer №4

Here's a neat way to showcase JSON information using Vue.js:

  • Insert a stringified json object inside a <textarea> utilizing the v-model directive
  • Display object properties by iterating through them 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>

https://i.stack.imgur.com/oiJY5.jpg

Answer №5

Incase the /api exists solely on the dev server, you have the option to create a vue.config.js file in the root directory of your app.

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));
      });
    }
  }
}

After adding these files, running npm run serve will provide the json object upon navigating to /api, while accessing the regular app content elsewhere.

Answer №6

Here's a simple solution:

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

Answer №7

Make sure to explore the benefits of using computed properties

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

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

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

<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e585b4b6e1d001e001b">[email protected]</a>/dist/vue.global.js"></script>

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

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

</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to transform this JSON string into a particular format?

When moving a string from view to controller, I have encountered an issue. Below is the ajax code I am using: var formData = $('#spec-wip-form, #platingspec-form').serializeArray(); var platingId = @Model.PlatingId; var form = JSON.s ...

How to eliminate an element from numerous arrays using jQuery?

Is it possible to use jq to remove all instances of a specific name from arrays within the input data? For example, removing "Name1" from the following: { "Category1": [ { "name": "Name1", "desc": "Desc1" }, { "name": "Name ...

Ways to display fresh information on webpage following data preservation in AngularJS

After saving some names in a form, I am attempting to display them alphabetically. Below is the method that contains all the saved data. The variable response.data should contain this data: function refreshNames() { NameService.getNames().then(func ...

When working with Typescript and Vue.js, it's important to ensure that properties are initialized before

Check out the following code snippet: export default class PrimitiveLink extends Vue { style = { // Reset display: 'inline-block', textDecoration: 'none', outline: 'none', // Theme ...this.themeStyle ...

Interacting with nested arrays and objects in JSON.net

Is there a way to access the nested array like timeseries.shortname in this JSON data? I have attempted it using the code below, but it seems to be encountering an issue. string url = "http://www.pegelonline.wsv.de/webservices/rest-api/v2/stations.json?in ...

Troubleshooting issue with AngularJS ng-repeat not functioning properly when using Object key value filter with ng-model

Is there a way to have an object with an ID as a key value pair? For example: friends = { 1:{name:'John', age:25, gender:'boy'}, 2:{name:'Jessie', age:30, gender:'girl'}, 3:{name:'Johanna', ag ...

What is the method for selecting the "save as" option while downloading a file?

Imagine a scenario where you click on a link like this: <a href="1.txt">Download</a> After clicking the link, a save as window will appear. Is it feasible to utilize JavaScript in order to simulate button clicks within that window? Alternativ ...

What is the best way to extract a single parameter from each element of a .json array using Python filtering?

Currently facing an issue with filtering an array obtained from the CoinGecko API. Here's how the array is structured: [ { "id": "01coin", "symbol": "zoc", "name": "01coin" }, ...

Is there a way in JavaScript or jQuery to display text from an array and switch to the next piece of text in the array with the click of a button?

I currently have an array containing 13 items, all of which are text. To display the text from the array, I am using: document.write(arrayname["0"]); However, I would like to implement a functionality where users can click a button to fade out the curren ...

When attempting to load a page in Mozilla, the initial DIV code fails to load

When trying to load a page in Mozilla, the first DIV code is not loading. I attempted to load HTML inside using: <div id="mainContent"></div> with the following call: if (destinationURL != null) { $.get(destinationURL, function(data) { ...

What is the best way to send a continuous stream of data in Express?

I've been attempting to configure an Express application to send the response as a stream. var Readable = require('stream').Readable; var rs = Readable(); app.get('/report', function(req,res) { res.statusCode = 200; ...

Utilizing variable values in HTML and CSS to enhance a website's functionality

My current project involves modifying an HTML web resource for use in Dynamics 365. I need to replace a static URL with a dynamic value obtained via Javascript, specifically: var URL = Xrm.Page.context.getClientUrl(); There are multiple instances within ...

Is it possible to create a single button that, upon clicking, fades in one image while simultaneously fading out another?

My goal is to have the blue square fade in on the first button click, then fade out while the red square fades in on the second click. Unfortunately, it seems that my current code is not achieving this effect. I'm open to any suggestions or help on h ...

Navigate through the JSON dataset

I am struggling with looping out JSON-data in an HTML list using PHP. The structure of the JSON data is as follows: { "msg": [ "msg text 1", "msg text 2", "msg text 3", "msg text 4", "msg text 5", "msg text 6" ] } My current P ...

Extract a property from a JSON object

Is there a way to access the href properties and use them to create multiple img elements with their sources set as the extracted href properties? I'm looking for a solution in either javascript or jQuery. I attempted the following code, but it didn& ...

The CORS policy has blocked access to the address due to security reasons

After spending the past 3 days trying to troubleshoot this issue, I am still unable to figure out why I keep encountering a CORS policy error when sending a request from a Vue Axios API call to the backend. Here is my current App Stack: Golang (Gin) Vue ...

Ways to apply the .not selector efficiently in jQuery

I have a situation with two separate divs, one named task1 and the other named task2. Each of these tasks contains panels with various names. Within task2, there is a duplicate name (Greg), who also belongs to the duplicate class. I'm trying to figure ...

Store the image URL in cache during AJAX loading

I have implemented an ajax slider to display images, and it is functioning perfectly. However, I am facing an issue with image caching. Since the images change dynamically using ajax, there is no cache available which causes a delay in displaying the new i ...

Using AngularJS to pass the output of a unique filter to another custom filter

I have successfully developed two custom filters and am attempting to utilize them both within an ng-repeat loop. Is there a way for me to pass the output of the first filter as an input for the second one? I attempted using 'as' keyword in ng- ...

Transforming rows into a JSON key/value pair in PostgreSQL is an effective way to organize

In my dataset, I have a simple table with columns labeled Key_1, Key_2, and Value. Each row contains different combinations of Key_1 and Key_2 values. My goal is to transform the rows from this table into a JSON structure that looks like this: { "my ...