0

I'm building a webapp that requires a JSON file as data. The person using my app in their website should be able to pass in a JSON file hosted on their server so that my app can read it.

In development, I just used import mydata from "./mydata.json", but this won't work in production. I tried to have a computed property that returns require (this.publicPath + this.datapath) (where this.publicPath is process.env.BASE_URL, but it's not able to find the file (if it's relevant, I'm using vue-cli to build).

The structure of my app is that I have a wrapper App.vue and then the main component, main-component.vue (so that I can pass a prop containing data to the main component).

What's the best way to do this? I've tried using a <script> tag in index.html, but apparently that's not supported with JSON. I don't want to use other libraries like jQuery.

(I'm thinking that I could have the user just import their file with the ES6 syntax by creating a new Vue component/app, but I'm not sure how to do that in pure HTML).

abias
  • 19
  • 6

2 Answers2

0

If you can try using a .js file that migh work and you can structure the data the same way as in a .json file, afterall a json is just a js object, also i had this problem while doing the same thing. DISCLAIMER: you might have to restructure your data to be in an exported variable if that is possible, like so:

export const myObj = {your json}

Komi
  • 450
  • 5
  • 14
0

As an extension of my comment: what you're looking for is to actually fetch the JSON from your server using an XMLHttpRequest. You can do this in a modern, ES6-manner using the Fetch API:

fetch('/path/to/your/json')
  .then(resp => resp.json())
  .then(data => {
    // Access the parsed JSON as `data`
    console.log(data);
  });
Terry
  • 63,248
  • 15
  • 96
  • 118
  • Thanks. I used `await` in my created method because I needed to force synchronous behavior – abias Dec 31 '20 at 22:13