How to read a JSON file without a server?

Asked

Viewed 4,741 times

6

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

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

I researched about 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 was hosted on a server. Is there any other way to do this? Why does that happen?

  • 2

    The site is hosted on Dropbox, so you have a server. JSON is also in Dropbox, right?

  • It is that Dropbox is limited only to client-side scripts and HTML, it is not able to run things from the server-side, rather the JSON file is bundled with html, css and javascript.

2 answers

6


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

To do this, just pass your JSON URL, say you’re at this Dropbox URL: https://dl.dropboxusercontent.com/u/6061295/stack/json.json, then you could retrieve the content from 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, getting something like this:

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

5

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, however local, 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 your 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 test in specific situations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.