Kendall
Kendall

Reputation: 5245

Import JSON into VueJS

I'm using wbepack to compile a VUEJS project in which I import a JSON file which has an array of objects into vueJS however when accessing it via the component the object appears to be empty.

import Jason from './some.json';
export defaults {
data(){ return { someArr: Jason } } }

I'm not getting any compile errors or any other reported errors.

What could cause the object someArr to be empty?

P.S. I am able to load the json via AJAX successfully

Upvotes: 7

Views: 16604

Answers (5)

Kalimwenjuma Robbyn
Kalimwenjuma Robbyn

Reputation: 42

Go to SCR and find a file named shims-vue.d.ts and add a JSON module like this.

    declare module '*.json' 
{
  const value: { [key: string]: any };
  export default value;
}

Upvotes: 3

lprend
lprend

Reputation: 142

This is how I do it:

In main.js:

import Conf from './static/app-conf.json';
Vue.prototype.$appConfig = Conf;

Now I can use that JSON-file whereever I need it by adding it to data:

    <template>
      <div>{{someText}}</div>
    </template>
    <script>        
        export default {
                name: 'Something',
                components: {},
                props: {},
                data: () => ({
                    someText: Vue.prototype.$appConfig.someText,
                }),
                computed: {},
                methods: {}
            };
    </script>

Upvotes: 1

GuyC
GuyC

Reputation: 6574

probably just a typo but you export default { not defaults

Assuming this isn't an issue are you exporting the JSON within ./some.json? i.e.

export default {
  "foo": "bar",
  ...
}

Upvotes: 1

AldoRomo88
AldoRomo88

Reputation: 2076

Install json loader with

npm install json-loader --save

then in your webpack.config file add this loader

module: {
    loaders: [
        {
            test: /\.json/,
            loader: 'json',
        }
    ],
}

Upvotes: 4

Marek Urbanowicz
Marek Urbanowicz

Reputation: 13644

This should work:

var yourJSONData= JSON.parse(Jason);

Upvotes: -1

Related Questions