Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access external json file objects in vue.js app

How to access JSON objects in the vue.js app I am new in this

import json from './json/data.json' 

the JSON file is loaded and now I have to access the objects within it

like image 888
Haroon Aslam Avatar asked Aug 08 '17 10:08

Haroon Aslam


People also ask

How do I view a JSON object?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.

How do I open a JSON file in console?

Approach: Create a JSON file, add data in that JSON file. Using JavaScript fetch the created JSON file using the fetch() method. Display the data on the console or in the window.


Video Answer


2 Answers

Just assign the import to a data property

<script>       import json from './json/data.json'       export default{           data(){               return{                   myJson: json               }           }       } </script> 

then loop through the myJson property in your template using v-for

<template>     <div>         <div v-for="data in myJson">{{data}}</div>     </div> </template> 

NOTE

If the object you want to import is static i.e does not change then assigning it to a data property would make no sense as it does not need to be reactive.

Vue converts all the properties in the data option to getters/setters for the properties to be reactive. So it would be unnecessary and overhead for vue to setup getters/setters for data which is not going to change. See Reactivity in depth.

So you can create a custom option as follows:

<script>           import MY_JSON from './json/data.json'           export default{               //custom option named myJson                  myJson: MY_JSON           }     </script> 

then loop through the custom option in your template using $options:

<template>         <div>             <div v-for="data in $options.myJson">{{data}}</div>         </div>     </template> 
like image 189
Vamsi Krishna Avatar answered Oct 10 '22 17:10

Vamsi Krishna


If your file looks like this:

[     {         "firstname": "toto",         "lastname": "titi"     },     {         "firstname": "toto2",         "lastname": "titi2"     }, ] 

You can do:

import json from './json/data.json'; // .... json.forEach(x => { console.log(x.firstname, x.lastname); }); 
like image 20
smarber Avatar answered Oct 10 '22 17:10

smarber