1

I have a .json file with the following structure:

{
       "title": "A"
       "name": "B"
},
{
           "title": "C"
           "name": "D"
},

and I want to use this data inside my Vue.js app. When I copy the data by hand to my my app, everything works:

<script>
  
  new Vue({
    el: '#app',
    data: {
      items: [
    {
           "title": "A"
           "name": "B"
    },
    {
         "title": "C"
         "name": "D"
    },
    ]

How can I load the data directly to my Vue app without having to copy the content of the .json file by hand?

(I'm using the CDN to load Vue.js and hence the usual "import" solutions do not work.)

jak
  • 184
  • 7

1 Answers1

3

You could do something like this:

new Vue({
    el: '#app',
    data: {
        items: null
    },
    created() {
        axios
            .get('./myJson.json')
            .then(response => {
                this.items = response.data;
            })
            .catch((e) => {
                console.error(e)
            })
    }
});

You can import Axios via CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.20.0/axios.min.js"></script>

And, make sure your JSON is well formatted:

[
  {
    "title": "A",
    "name": "B"
  },
  {
    "title": "C",
    "name": "D"
  }
]
hatef
  • 5,491
  • 30
  • 43
  • 46
  • 1
    You can use `fetch` instead of axios so you don't have to import another lib. – Konrad Aug 31 '20 at 08:44
  • 2
    True @KonradLinkowski - However, I do like _axios_ over _fetch_ for [several](https://stackoverflow.com/a/50326744/2568469) reasons. – hatef Aug 31 '20 at 08:48