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();
});

推荐答案

您可以判断响应的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(并且不信任标题),您可以始终将响应接受为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/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
  }
}

Json相关问答推荐

Elasticsearch Go客户端错误:无效的SON格式:在中间件中索引文档时出错

无法从JSON解析ZonedDateTime,但可以使用格式化程序很好地解析

Jolt Spec 跳过数组中的第一个元素

APIM 生成 JsonArray 到 EventHub

如何在JQ中展平多维数组

如何使用 serde_json 构建有状态的流式解析器?

JSONPath:查找子项目条件在字符串列表中的项目

如何从 json 中获取单个元素?

将 colly 包输出文本添加到 golang 中的映射

如何在循环中传递列表(会话(字符串属性))以在 Gatling Scala 中创建批量 Json 请求

使用 json 值过滤 Django 模型

错误字符串的长度超过了maxJsonLength属性设置的值

为什么在我们有 json_encode 时使用 CJSON 编码

使用 Spring 和 JsonTypeInfo 注释将 JSON 反序列化为多态对象模型

有没有办法使用 Jackson 将 Map 转换为 JSON 表示而不写入文件?

使用 ajax 将 JSON 发送到 PHP

JSON.parse 返回字符串而不是对象

从 Json 对象 Android 中获取字符串值

YAML 将 5e-6 加载为字符串而不是数字

FastAPI:如何将正文读取为任何有效的 json?