我使用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();
});
答案 0 :(得分:95)
您可以检查回复的content-type
,如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
并自行解析:
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
}
});
<强>异步/ AWAIT 强>
如果你正在使用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
}
}
答案 1 :(得分:4)
您可以使用帮助程序功能来做到这一点:
header
然后像这样使用它:
const parseJson = async response => {
const text = await response.text()
try{
const json = JSON.parse(text)
return json
} catch(err) {
throw new Error("Did not receive JSON, instead received: " + text)
}
}
这将引发错误,因此您可以fetch(URL, options)
.then(parseJson)
.then(result => {
console.log("My json: ", result)
})
进行操作。
答案 2 :(得分:0)
使用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;
}