29

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.

2
  • Alert undefined for me., what was the status, did it produce an error in your console? Commented Jun 7, 2013 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! Commented Jun 7, 2013 at 19:31

7 Answers 7

60

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]);
Sign up to request clarification or add additional context in comments.

7 Comments

I didn't realise you could pass a URI to JSON.parse and have it perform a REQUEST for you, where is this documented?
yeah.. edit was on the way.. guess should have answered after the fact
for your pure js alert is not starting also
XMLHttpRequest cannot load file:///.../data.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
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?
|
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);
  }
}

4 Comments

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.
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check xhr.spec.whatwg.org.
@Evorlor Change the false on line 2 to true. Otherwise it's a synchronous operation.
@Evorlor here is a closer link to what you are writing that one should use async and not sync.
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);
});

Comments

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.

1 Comment

.. but does not work for me, see my comments to the other posts.
0

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

1 Comment

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:/// ...
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);

1 Comment

.. but does not work for me, see my comments to the other posts. And .. what is the added value here compared to this? Looks like copy-paste. Welcome to SO.
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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.