Load a JSON file without server

╄→гoц情女王★ 提交于 2020-01-30 11:01:30

问题


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 say things like "rename to myjson.js" and add var data = " yourjson" and in your html file include myjson.js and acces the variable data. This is not what I want. I want to load in the JSON file without renaming/altering it and without a webserver (No AJAX).

Can anyone help me?

  $.getJSON('myjson.json', function(myjson) {...}

Will not work.

Including css and js functions is so easy why is it so impossible to access a locally stored json file without a webserver?

Edit: json file first lines

[{"participants": ["a", "b"], "conversation": [{"sender": "b", "created_at": "2019-09-23T22:04:42.083698+00:00", "text": "xxx"},

Edit: adding my js for clarification

Edit: Can't because I'm on mobile and code formatting doesn't work here


回答1:


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.




回答2:


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




回答3:


I'm not quite sure what you are aiming to do. But you could save your JSON as a static file, and use a dynamic import to "load" it.

There is a great example on: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import



来源:https://stackoverflow.com/questions/58207743/load-a-json-file-without-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!