How to read a JSON using ONLY JavaScript? [closed]

1

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

    
asked by anonymous 10.02.2017 / 21:17

2 answers

1

Reading a file from the disk is asynchronous, so you need 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);
}

Usage Mode

lerArquivo("caminho-do-arquivo-aqui", function(texto){
    var dado = JSON.parse(texto);
    console.log(dado);
});
    
11.02.2017 / 00:35
1

In addition to the basic example you have to worry about the file cache (for your question, I recognize it to be a file), remembering that it must be being hosted (browser does not allow requests to the device's locations). If you want to avoid caching I recommend requesting a file preprocessed by the server (for example, PHP), to define a response header that ends with the length of the file cache (there are several examples easy to find), or on another occasion , 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 of how to define it (% with%).

The @LucasKauer response will also work to interpret JSON, but currently it is not getting the interpretation result ( request.setRequestHeader('Content-Type', 'application/x-javascript; charset:Codificação') returns the contents of the file, but rawFile.responseText returns the content interpreted automatically by the browser).

It is also possible to minimize callbacks of asynchronous requests using ES6-generating functions (so 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();
    
11.02.2017 / 00:34