read a local json file in my extension

4,253 views
Skip to first unread message

jack

unread,
Jul 31, 2015, 10:54:57 AM7/31/15
to Chromium-extensions
hi,

how can i read a local json file in my extension?

I tried:

$.getJSON("file.json", function(json_data) {
                    // json_data
                });

however, i cannot access json_data outside the callback function. 

to make a deep copy of json_data in a global variable that can be accessed outside callback function, i tried $.extend(true,target, json_data) and JSON.parse(JSON.stringify(json_data)) but with no success.

Can you, please, tell me what's wrong?

Thanks  a lot in advance.

Antony Sargent

unread,
Aug 3, 2015, 1:57:59 PM8/3/15
to jack, Chromium-extensions
Are you sure you're getting the JSON content? E.g. something like this should work:

var xhr = new XMLHttpRequest;
xhr.open("GET", chrome.runtime.getURL("manifest.json"));
xhr.onreadystatechange = function() {
  if (this.readyState == 4) {
    console.log("request finished, now parsing");
    window.json_text = xhr.responseText;
    window.parsed_json = JSON.parse(xhr.responseText);
    console.log("parse results:");
    console.dir(window.parsed_json);
  }
};
xhr.send();



--
You received this message because you are subscribed to the Google Groups "Chromium-extensions" group.
To unsubscribe from this group and stop receiving emails from it, send an email to chromium-extens...@chromium.org.
To post to this group, send email to chromium-...@chromium.org.
Visit this group at http://groups.google.com/a/chromium.org/group/chromium-extensions/.
To view this discussion on the web visit https://groups.google.com/a/chromium.org/d/msgid/chromium-extensions/79577086-fa76-4a7d-9243-22151ef3ca6f%40chromium.org.
For more options, visit https://groups.google.com/a/chromium.org/d/optout.

Wolf War

unread,
Aug 3, 2015, 2:03:34 PM8/3/15
to Chromium-extensions
another solution would be:

chrome.runtime.getPackageDirectoryEntry(function(root) {
root.getFile("MY_FILE.json", {}, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var myFile = JSON.parse(this.result);
/*do here whatever with your JS object(s)*/
};
reader.readAsText(file);
});
});
});
Reply all
Reply to author
Forward
0 new messages