如何检查 fetch 的响应是否是 javascript 中的 json 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37121301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if the response of a fetch is a json object in javascript
提问by Sibelius Seraphini
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 polyfill 从 URL 检索 JSON 或文本,我想知道如何检查响应是 JSON 对象还是只是文本
fetch(URL, options).then(response => {
// how to check if response has a body of type json?
if (response.isJson()) return response.json();
});
回答by nils
You could check for the content-type
of the response, as shown in this MDN example:
您可以检查content-type
响应的 ,如此 MDN 示例所示:
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
});
}
});
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:
如果您需要绝对确定内容是有效的 JSON(并且不信任标头),您总是可以只接受响应text
并自己解析它:
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/await
,您可以以更线性的方式编写它:
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
}
}
回答by Rakesh Soni
Use a JSON parser like JSON.parse:
使用像 JSON.parse 这样的 JSON 解析器:
function IsJsonString(str) {
try {
var obj = JSON.parse(str);
// More strict checking
// if (obj && typeof obj === "object") {
// return true;
// }
} catch (e) {
return false;
}
return true;
}