Load a JSON file without server

后端 未结 2 1171
清歌不尽
清歌不尽 2020-12-12 07:43

I have a big json file (+-10mb). I want to load in this json file (myjson.json) in a Javascript function located in a HTML webpage. I found a lot of answers on google that s

相关标签:
2条回答
  • 2020-12-12 08:01

    I think you are looking for FileReader: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

    If you have it working, take a look at JSON.parse(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

    0 讨论(0)
  • 2020-12-12 08:13

    Unfortunately, both XHR and the Fetch API are inextricably tied to HTTP, and cannot be used to load a resource from a relative path unless an HTTP server is involved. If you're loading your page via a file: URL, you won't be able to use XHR or Fetch to get that data.

    There are only two methods available to you:

    • Switch to JavaScript instead of regular JSON and use a <script> tag (as previously suggested to you in another answer)

    • Allow the user to drag/drop the JSON file (or use <input type="file">) to get a File reference that you can then load.

    0 讨论(0)
提交回复
热议问题