如何检查提取的响应是否是javascript中的json对象 [英] How to check if the response of a fetch is a json object in javascript
本文介绍了如何检查提取的响应是否是javascript中的json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用抓取polyfill从URL检索JSON或文本,我想知道如何检查响应是JSON对象还是仅文本
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();
});
推荐答案
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 => {
// process your JSON data further
});
} else {
return response.text().then(text => {
// this is text, do something with it
});
}
});
如果您需要绝对确定内容是有效的JSON(并且不信任标头),则始终可以将响应作为text
接受并自己解析:
If you need to be absolutely sure that the content is 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())
.then(text => {
try {
const data = JSON.parse(text);
// Do your JSON handling here
} catch(err) {
// It is text, do you 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); // Fetch the resource
const text = await response.text(); // Parse it as text
const data = JSON.parse(text); // Try to parse it as json
// Do your JSON handling here
} catch(err) {
// This probably means your response is text, do you text handling here
}
}
这篇关于如何检查提取的响应是否是javascript中的json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文