28

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.

karthikr
  • 97,368
  • 26
  • 197
  • 188
jagger
  • 532
  • 1
  • 5
  • 13
  • `Alert undefined for me.`, what was the `status`, did it produce an error in your _console_? – Paul S. Jun 07 '13 at 19:21
  • Finally, `if (request.status == 200)` made issues for me. It gives 0 even if it finds the file. If i delete it, all is ok. Thanks for everyone! – jagger Jun 07 '13 at 19:31

7 Answers7

59

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]);
karthikr
  • 97,368
  • 26
  • 197
  • 188
  • I didn't realise you could pass a _URI_ to `JSON.parse` and have it perform a `REQUEST` for you, where is this documented? – Paul S. Jun 07 '13 at 19:15
  • yeah.. edit was on the way.. guess should have answered after the fact – karthikr Jun 07 '13 at 19:17
  • for your pure js alert is not starting also – jagger Jun 07 '13 at 19:27
  • my_JSON_object.result is undefined. You would access the Javascript created from the JSON file through my_JSON_object directly instead. – Fabien Snauwaert Oct 28 '13 at 15:18
  • 14
    XMLHttpRequest cannot load file:///.../data.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. – Dagrooms Jun 04 '15 at 13:52
  • 2
    I get this same `XMLHttpRequest` error when developing locally. Are there any non-network calls to load the local JSON file and parse it for use within client-side JavaScript? – Gaurav Apr 19 '16 at 21:34
  • Did not work for me, but [solution below](https://stackoverflow.com/a/23419205/1705829) with the asynchronous check if the json is ready worked. I get without it an `unexpected end of JSON input` error which tells me that the json parse starts but does not finish before the next order starts. – Timo Mar 06 '22 at 08:28
10

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);
  }
}
O. Jones
  • 103,626
  • 17
  • 118
  • 172
josephnvu
  • 101
  • 1
  • 2
  • 1
    Welcome to SO. Good answer. I edited it because it's best when an answer stands alone. Dialogue about other answers is appropriate in comments. – O. Jones May 02 '14 at 01:27
  • 1
    Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/. – Evorlor Apr 08 '15 at 15:04
  • 6
    @Evorlor Change the false on line 2 to true. Otherwise it's a synchronous operation. – Todd Apr 21 '15 at 05:36
  • @Evorlor [here](https://xhr.spec.whatwg.org/#the-open()-method) is a closer link to what you are writing that one should use `async` and not `sync`. – Timo Mar 06 '22 at 08:38
4

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);
});
Community
  • 1
  • 1
maazza
  • 7,016
  • 15
  • 63
  • 96
3
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.

Sumukh Bhandarkar
  • 386
  • 1
  • 5
  • 14
0

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

Kristaps Karlsons
  • 482
  • 1
  • 7
  • 22
  • Actually, i make it in titanium webview, so normally resources should be root path. If i make document.location.pathname and start in browser i will for sure get file:/// ... – jagger Jun 07 '13 at 19:19
0

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);
Miorita
  • 340
  • 3
  • 12
  • .. but does not work for me, see my comments to the other posts. And .. what is the added value here compared to [this](https://stackoverflow.com/a/16991355/1705829)? Looks like copy-paste. Welcome to SO. – Timo Mar 06 '22 at 08:43
0

Even if long time answerd, I here is another that does not need to create a request. I created a lg.js script containing a class and some functions (setLg, de, en, ...) Each "lg" function (de, en, fr, ...) provides a json object containing the translations.

"use strict"
class Lg {
  constructor() { this.tr = this.en(); }
  setLg(l) {
    if l == "de" this.tr = this.de(); 
    if l == "en" this.tr = this.en();
  de() {
   "item": "Artikel",
   "login": "Login"
  }
  en() {
   "item": "Item",
   "login": "login"
  }
 }
 var lg = new Lg(); //global accessable object

You can then use it by "lg.tr.item" You could also create a small function, that checks if the "key" is in the JSON object to have some kind of error checking.

Der Achim
  • 66
  • 5
  • This example is too far away from the question I think. An example should be used without any effort and here, I need `l` var to work with it. Welcome to SO. – Timo Mar 06 '22 at 08:42