How to read a JSON file without a server?

6

I'm developing a simple static website with html, css and javascript hosted in Dropbox, using javascript with the JQuery framework and trying to read a JSON file.

var jqxhr = $.getJSON( "example.json", function() {
  console.log( "success" );
});

I've researched and realized that this is an AJAX call to a local resource through an HTTP request, and that it would only be possible if the site were hosted on a server. Is there any other way to do this? Why does this happen?

    
asked by André N. Darcie 12.10.2015 в 02:45

2 answers

6

If you already have JSON in a file, in the same DropBox, you can use getJSON as you mentioned, the DropBox is your static file server;)

To do this, simply pass the URL of your JSON, let's say it's in this DropBox URL: link , then you could retrieve the contents of JSON and its properties like this:

$.getJSON("https://dl.dropboxusercontent.com/u/6061295/stack/json.json", function(json) {
    console.log('id: ' + json.id);
    console.log('nome: ' + json.nome);
});

Now, if you have JSON content in your HTML page, you can use parseJSON , something like this:

var json = '{"id":1, "nome": "Bruno"}';
var obj = $.parseJSON(data);
console.log('id: ' + obj.id);
console.log('nome: ' + obj.nome);
    
12.10.2015 / 03:17
4

Depending on the browser you are using, access to local resources via AJAX will be blocked even if your page is also stored in the same location.

If the page was accessed through a URL, even a local one, the problem would not occur. A simple solution is to install a local server, such as Apache or Nginx. So you can edit the files and see the changes immediately reliably and securely.

Alternatively, if you're using Google Chrome, run the browser with a parameter that disables such restriction . For example:

/dir/chrome --allow-file-access-from-files

However, I would not recommend this solution other than for some simple testing in specific situations.

    
12.10.2015 в 03:05