readJSON - step2
with Fetch
by Julien Roche
HTML
<pre></pre>
JavaScript
var readJSON = function (url) {
return fetch(readJSON.base + url)
.then(function (response) {
return response.text();
})
.then(function (responseText) {
return typeof JSON5 !== 'undefined' ? JSON5.parse(responseText) : JSON.parse(responseText);
})
.catch(function () {
return null;
});
};
readJSON.base = '/base/';
if (typeof exports !== 'undefined') {
exports.readJSON = readJSON;
}
// ------------------------------------------------------------------------------------------------
// Testing
readJSON.base = 'https://jsonplaceholder.typicode.com/';
readJSON('posts/1')
.then(function (json) {
document.querySelector('pre').innerText = JSON.stringify(json, null, '\t');
});