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

The package.json file is missing the "exports" main, causing the Error [ERR_PACKAGE_PATH_NOT_EXPORTED] to be displayed

Can anyone help me resolve the 'Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in package.json' issue? I've been struggling to fix it despite receiving assistance. The problem is quite baffling and the more I dwel ...

Vue Router configuration functions properly when accessed through URL directly

I need guidance on how to handle the routing setup in this specific scenario: Below is the HTML structure that iterates through categories and items within those categories. The <router-view> is nested inside each category element, so when an item i ...

Execute the jQuery function to submit the form via AJAX once the validation process has been

I am currently working on a form and implementing the jQuery validate plugin for validation purposes. My aim is to trigger the ajax code to submit the form only after the validation process is successfully completed. How can I achieve the following: // T ...

Using Vue/Nuxt, you can schedule the execution of a function on a specific page by employing either $nextTick or

I have a function that I want to call every 10 seconds on my page when it is mounted. However, even after leaving the page, the function continues to run indefinitely. mounted() { if(this.user_authenticated) { this.$nextTick(function () ...

I am curious about how to implement overflow:hidden along with position:sticky in React.js

My attempt to address the white space issue caused by a navbar I created led me to try using overflow:hidden. The navbar is generated using the Header component, and I desired for it to have a position: sticky attribute. However, I realized that I cannot ...

Ways to address a buffered data problem in Websocket Rxjs. When trying to send a message, it is not being received by the server and instead is being stored in a

Currently, I am utilizing Websocket Rxjs within my application. The connection is successfully established with the server, and upon subscribing to it, all data is received in an array format. However, when attempting to send data back to the server, it se ...

Generate list items based on a PHP array using JavaScript

Upon fetching data from my database, I receive a PHP array structured as follows: $dbResult = array([0] => array([a] => 1 [b] => 1 [c] => 1) [1] => array([a] => 2 [b] => 2 [c] => 2) [3] => arr ...

Guide on uploading images to a NodeJS server from an Angular 2+ application

I have a NodeJS rest-API that can handle both images and text content in the same function. Currently, I am using multer in my NodeJS server to manage image uploads along with text content. Below is an example code snippet showcasing how I am handling this ...

What is the best way to interpret a JSON with nested structure?

I can't seem to find any errors in the code below, but I keep receiving an error message stating "item._highlightResult.map is not a function". {items.map((item, index) => ( <li key={index}><a href={item.story_url} target="_blank& ...

There are a total of 152 issues found in the index.tsx file within the react

Despite everything working correctly, I am continuously encountering these errors. Is this a common occurrence? What steps can I take to resolve them? I have developed my react application using Javascript instead of Typescript; however, I don't belie ...

Enhance the numerical value displayed in jQuery UI tooltips

I have folders with tooltips displaying text like '0 entries' or '5 entries' and so on. I am looking for a way to dynamically update this tooltip number every time an item is added to the folder. The initial count may not always start a ...

Transforming a JSON file into a pandas dataframe

I am seeking assistance with parsing JSON files into a pandas dataframe. Specifically, I would like to create one column containing the words present in the text and another column containing the corresponding entity type. If the word matches the value of ...

Expanding on the nested document in mongoose

I have been working on setting up a nested mongoose document configuration in the following manner: models/data.js var mongoose = require('mongoose'); var addresses = new mongoose.Schema({ "street": String, "city": String, "state": Stri ...

What is the best way to display a template after submitting data via AJAX in the Flask framework?

Encountering an issue where I am unable to open render_template after posting data with ajax. Below is my ajax code: if ($(this).attr("value") == "button-three") { var skoring = getRadioVal(document.getElementById('mentodeNegasi'),'neg ...

"Exploring the differences between sending a JSON post request with multiple parameters to a Web

Our transition from MVC to WebApi for data serving involves changing the controller structure, as shown in the example below. MVC: OfficeController : Controller { [HttpPost] public IEnumerable<Employee> SetSalary(string badge, string salary ...

Loop through a nested array and output the playerId, playerName, and playerCategory for each player

update 3: After thorough debugging, I finally found the solution and it has been provided below. let values = { "sportsEntitties": [{ "sportsEntityId": 30085585, "sportsEntityName": "490349903434903490", "sportsEntityStartDate": "7878 ...

Is it acceptable to designate the db instance as a global variable so that it is always accessible without requiring the "require" statement in Node.js?

I am just starting my journey with "node js" and I am currently working on a program that requires a database model similar to "wpdb" in WordPress. Should I create it as a global variable or use the "require" statement only when needed? Your help in provi ...

Dropzone.js only allows one audio file and one image thumbnail file to be uploaded simultaneously

Is there a way to limit the types of files that can be uploaded through Dropzone.js? Specifically, I want to restrict users to uploading only one image and one audio file. ...

Is it possible to pass parameters in the .env file in Node.js?

I am storing my file users.env inside routes/querys/users.env module.exports = { GET_USERS: "SELECT * FROM users", CREATE_USER: "INSERT INTO users ("id", "first_name", "last_name", "active") VALUES (NULL, '%PARAM1%', '%PARAM2%', & ...

Issue encountered when utilizing SwiftyJSON to parse JSON containing Unicode characters

When the API responds, this is the data I receive: 2015-08-31 7:29:45 [GDMNetManagerSMB.swift-228]: response: Optional(<NSHTTPURLResponse: 0x7fd6c507c6a0> { URL: ... } { status code: 200, headers { Age = 0; "Cache-Control" = "max-age ...