Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  122] [ 7]  / answers: 1 / hits: 143941  / 8 Years ago, mon, may 9, 2016, 12:00:00

I'm using fetch polyfill to retrieve a JSON or text from a URL, I want to know how can I check if the response is a JSON object or is it only text



fetch(URL, options).then(response => {
// how to check if response has a body of type json?
if (response.isJson()) return response.json();
});

More From » json

 Answers
20

You could check for the content-type of the response, as shown in this MDN example:


fetch(myRequest).then(response => {
const contentType = response.headers.get("content-type");
if (contentType && contentType.indexOf("application/json") !== -1) {
return response.json().then(data => {
// The response was a JSON object
// Process your data as a JavaScript object
});
} else {
return response.text().then(text => {
// The response wasn't a JSON object
// Process your text as a String
});
}
});

If you need to be absolutely sure that the content is a valid JSON (and don't trust the headers), you could always just accept the response as text and parse it yourself:


fetch(myRequest)
.then(response => response.text()) // Parse the response as text
.then(text => {
try {
const data = JSON.parse(text); // Try to parse the response as JSON
// The response was a JSON object
// Do your JSON handling here
} catch(err) {
// The response wasn't a JSON object
// Do your text handling here
}
});

Async/await


If you're using async/await, you could write it in a more linear fashion:


async function myFetch(myRequest) {
try {
const reponse = await fetch(myRequest);
const text = await response.text(); // Parse it as text
const data = JSON.parse(text); // Try to parse it as JSON
// The response was a JSON object
// Do your JSON handling here
} catch(err) {
// The response wasn't a JSON object
// Do your text handling here
}
}

[#62249] Friday, May 6, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dequant

Total Points: 88
Total Questions: 99
Total Answers: 95

Location: Ukraine
Member since Sun, Dec 13, 2020
4 Years ago
dequant questions
;