gpt4 book ai didi

javascript - 如何检查获取的响应是否是javascript中的json对象

转载 作者:IT老高 更新时间:2023-10-28 12:44:09 26 4
gpt4 key购买 nike

我正在使用 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();
});

最佳答案

您可以检查响应的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 => {
// 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
});
}
});

如果您需要绝对确定内容是有效的 JSON(并且不信任 header ),您可以随时将响应作为 text 接受并自己解析:

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,您可以以更线性的方式编写它:

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
}
}

关于javascript - 如何检查获取的响应是否是javascript中的json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37121301/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com