How to read a JSON using JAVASCRIPT ONLY?

Asked

Viewed 634 times

1

I want to read and present in a.log console the information that is inside my . JSON, but without using jquery or other frameworks. Basic code.

  • Where is this Json? On the server? External? Have some code to show us what you are trying?

  • From a look here: http://www.w3schools.com/xml/xml_http.asp

2 answers

1

In addition to the basic example you have to worry about the file cache (by your question, I recognize that it is a file), remembering that it must be hosted (the browser does not allow requests on the device locations). If you want to avoid caching, I recommend requesting a file pre-processed by the server (for example, PHP), to define a response header that ends the duration of the file cache (there are several easy-to-find examples), or at another time, you can versionalize the request URL (in several ways).

Remembering that it is also important to know the encoding used in the file, to get your expected Unicode characters. Here are some examples how to define it (request.setRequestHeader('Content-Type', 'application/x-javascript; charset:Codificação')).

The @Lucaskauer response will also work to interpret JSON, but currently it is not getting the result of the interpretation (rawFile.responseText returns the contents of the file, but rawFile.response returns content automatically interpreted by the browser).

It is also possible to minimize asynchronous request callbacks using ES6 generating functions (from what I know there is something similar in Ecmascript 5, using the language API itself).

// Requisição assíncrona
var request = new XMLHttpRequest;
request.open('GET', 'file.json', true);

function onReadyStateChange () {
    if (request.readyState === 4 && request.status === 200) {
        console.log(JSON.parse(request.responseText));
    }
}
request.addEventListener('readystatechange', onReadyStateChange);
request.send();
  • 1

    Thank you, man. I managed to do something very similar! It helped a lot!

1

The read of a disk file is asynchronous, so it is necessary to inform a callback function.

function lerArquivo(arquivo, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", arquivo, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}

Method of Use

lerArquivo("caminho-do-arquivo-aqui", function(texto){
    var dado = JSON.parse(texto);
    console.log(dado);
});

Browser other questions tagged

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