Using Fetch API to Access JSON

Using Fetch API to Access JSON

The Fetch API returns a response stream in the promise. The response stream is not JSON, so trying to call JSON.parse on it will fail. To correctly parse a JSON response, you'll need to use the response.json function. This returns a promise so you can continue the chain.

fetch('http://jsonplaceholder.typicode.com/users', { 
method: 'GET'
})
.then(function(response) { return response.json(); })
.then(function(json) {
// use the json
});

Receive and process JSON using fetch API in Javascript

A fetch API is provided in the global window scope in javascript, with the first argument being the URL of your API, it's Promise-based mechanism.

Simple Example

// url (required)
fetch('URL_OF_YOUR_API', {//options => (optional)
method: 'get' //Get / POST / ...
}).then(function(response) {
//response
}).catch(function(err) {
// Called if the server returns any errors
console.log("Error:"+err);
});

In your case, If you want to receive the JSON response

 fetch('YOUR_URL')
.then(function(response){
// response is a json string
return response.json();// convert it to a pure JavaScript object
})
.then(function(data){
//Process Your data
if (data.is_taken_email)
alert(data);
})
.catch(function(err) {
console.log(err);
});

Example using listener based on XMLHttpRequest

function successListener() {    var data = JSON.parse(this.responseText);    alert("Name is: "+data[0].name);  }
function failureListener(err) { console.log('Request failed', err); }
var request = new XMLHttpRequest(); request.onload = successListener; request.onerror = failureListener; request.open('get', 'https://jsonplaceholder.typicode.com/users',true); request.send();

How to store the json data from fetch API request into a global variable - javascript

While I understand that you'd like a global variable for your data, I would advise against polluting the global namespace (see also: [1], [2], [3] and [4]).

You could instead encapsulate everything in an Immediately Invoked Function Expression (IIFE), and have your fetch method inside of it with all of the code related to that area of your program.

Then, by rearranging @alexanderdavide's answer, we get the following code:

(async () => {
let data_local;

const getData = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const data = await response.json();
dataGlobal = data;
return data;
};

await getData();
console.log(data_local);

// your code goes here...
})();

You could also use the following alternative as well:

(async () => {
const getData = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const data = await response.json();
dataGlobal = data;
return data;
};

let data_local = await getData();
console.log(data_local);

// your code goes here...
})();

That way your data_local variable would be available to everything beneath it but not outside of the IIFE itself, protecting the global namespace while allowing multiple methods access to the same variable without using callbacks with a data argument.

NOTE: please be careful if/when you change the data variable, you might end up changing it multiple times and inadvertently causing an error because of missing / improperly formatted data.

Good luck.

return json value through fetch function

You are attempting to set the value of PlayerName before the fetch has resolved.

If you return the promise from your PlayerName function then you are able to set the innerHtml once the promise is resolved.

function PlayerName(id) {
var url = `https://apiurl/Player/${id}`;
return fetch(url)
.then(response => response.json())
.then(data => {
console.log(`${data.FirstName} ${data.LastName}`)
return data.FirstName + ' ' + data.LastName;
})
}

PlayerName('10000439').then(player => {
var nameDiv = document.querySelector('#PlayerName')
nameDiv.innerHTML = `Batting: ${player}`;
})

Alternatively you can wrap the entire function to execute asynchronously

async function PlayerName(id) {
var url = `https://apiurl/Player/${id}`;
return fetch(url)
.then(response => response.json())
.then(data => {
console.log(`${data.FirstName} ${data.LastName}`)
return data.FirstName + ' ' + data.LastName;
})
}

var curBatter = document.querySelector('#batterPlayerName');
var curPitcher = document.querySelector('#pitcherPlayerName');

(async () => {
curBatter.innerHTML = await PlayerName('10000439');
curPitcher.innerHTML = await PlayerName('10000526');
})();

How can I fetch one value type from the JSON data and display in a list?

EDIT (based on comments):
It appears you are going to fetch a REST endpoint, so you can not fetch only parts of a response (as opposed to e.g. graphQL) so all you can do is selectivelly include/exclude data that you need. I updated the code to reflect this.

The code is good but you should always try to code your app with data as close as possible to the real one. Using a data source with a different shape from what you will end up using will always bring in bugs and changes in code.

I updated your example to use the data you provided instead of fetching from the API you were using. Take a look into the nested loop in the updateHTML() method.

const src = {
"code": "200",
"drawdate": "1 มีนาคม 2564",
"result": [
{
"id": "lotto_one",
"name": "รางวัลที่ 1",
"reword": 6000000,
"amount": 1,
"number": "835538"
},
{
"id": "lotto_first_three",
"name": "เลขหน้า 3 ตัว",
"reword": 4000,
"amount": 2,
"number": [
"290",
"838"
]
},
{
"id": "lotto_last_three",
"name": "เลขท้าย 3 ตัว",
"reword": 4000,
"amount": 2,
"number": [
"051",
"806"
]
},
{
"id": "lotto_last_two",
"name": "เลขท้าย 2 ตัว",
"reword": 2000,
"amount": 1,
"number": "73"
},
{
"id": "lotto_side_one",
"name": "รางวัลข้างเคียงรางวัลที่ 1",
"reword": 2000,
"amount": 1,
"number": [
"835537",
"835539"
]
},
{
"id": "lotto_two",
"name": "รางวัลที่ 2",
"reword": 200000,
"amount": 5,
"number": [
"316827",
"731177",
"743731",
"788652",
"923096"
]
},
]
};
const output = document.querySelector('.output');
/*
// Use local data instead
fetch('https://api.chucknorris.io/jokes/random', {
headers: {
"Content-Type": "application/json",
"x-api-key": "pass",
},
})
.then(response => response.json())
.then(updateHTML);
*/
function updateHTML(data) {

// Get the object entries - and array of key/value pairs
const entries = Object.entries(data);

// Iterate over the entries and return a new array
// of strings created from the key/value using a
// template string.
const rows = data.map((entry) => {
return Object.keys(entry).map((key) => {
let value = entry[key];
if (key === 'number') {
if (Array.isArray(value)) {
value = value.join(' | ');
}
return `
<tr>
<td class="heading">${key}</td>
<td>${value}</td>
</tr>
`;
}
}).join('');

});

// Create a new HTML string by `join`ing up the row array
// and adding it to a new string
const html = `<table><tbody>${rows.join('')}</tbody></table>`;

// Insert the HTML into the page
output.insertAdjacentHTML('beforeend', html);
}
updateHTML(src.result);
<div class="output"></div>

Fetch json data from url and write in a file

jsondata is a redundant variable. Here is a rewrite of your fetch().then().then() which leverages fs.writeFile() in the second .then().

I used node-fetch for this implementation, but it should work in a browser environment as well.

fetch('http://somewebsite.null')
.then((response) => {
return response.json();
})
.then((json) => {
fs.writeFile('./test.json', JSON.stringify(json), (err) => {
if (err) {
throw new Error('Something went wrong.')
}
console.log('JSON written to file. Contents:');
console.log(fs.readFileSync('test.json', 'utf-8'))
})
})


Related Topics



Leave a reply



Submit