JSON Parse File Path

2019-01-22 04:11发布

I'm stuck trying to get the correct path to the local file. I have the following directories:

Resources ->
   data ->
       file.json
   js ->
     folder ->
        script.js
   html ->
      folder ->
         file1.html

I'm executing script.js from file1.html, with js code:

var answers = JSON.parse('../../data/file.json');
alert(answers);

But it doesn't work, even alert is not starting. What is wrong?

Also I've tried this:

function readJSON(file) {
    var request = new XMLHttpRequest();
    request.open('GET', file, false);
    request.send(null);
    if (request.status == 200)
        return request.responseText;
};

var temp = readJSON('../../data/file.json');
alert(temp);

Alert undefined in this case.

6条回答
Fickle 薄情
2楼-- · 2019-01-22 04:19

If Resources is the root path, best way to access file.json would be via /data/file.json

查看更多
该账号已被封号
3楼-- · 2019-01-22 04:21

This solution uses an Asynchronous call. It will likely work better than a synchronous solution.

var request = new XMLHttpRequest();
request.open("GET", "../../data/file.json", false);
request.send(null);
request.onreadystatechange = function() {
  if ( request.readyState === 4 && request.status === 200 ) {
    var my_JSON_object = JSON.parse(request.responseText);
    console.log(my_JSON_object);
  }
}
查看更多
祖国的老花朵
4楼-- · 2019-01-22 04:25

Since it is in the directory data/, You need to do:

file path is '../../data/file.json'

$.getJSON('../../data/file.json', function(data) {         
    alert(data);
});

Pure JS:

   var request = new XMLHttpRequest();
   request.open("GET", "../../data/file.json", false);
   request.send(null)
   var my_JSON_object = JSON.parse(request.responseText);
   alert (my_JSON_object.result[0]);
查看更多
相关推荐>>
5楼-- · 2019-01-22 04:28

Loading local JSON file

Use something like this

$.getJSON("../../data/file.json", function(json) {
    console.log(json); // this will show the info in firebug console 
    alert(json);
});
查看更多
做个烂人
6楼-- · 2019-01-22 04:33

My case of working code is:

var request = new XMLHttpRequest();
request.open("GET", "<path_to_file>", false);
request.overrideMimeType("application/json");
request.send(null);
var jsonData = JSON.parse(request.responseText);
console.log(jsonData);
查看更多
干净又极端
7楼-- · 2019-01-22 04:34
var request = new XMLHttpRequest();
request.open("GET","<path_to_file>", false);
request.send(null);
var jsonData = JSON.parse(request.responseText);

This code worked for me.

查看更多
登录 后发表回答