如何检查 fetch 的响应是否是 javascript 中的 json 对象

问题描述 投票:0回答:6

我正在使用 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();
});
javascript json fetch-api
6个回答
326
投票

您可以检查响应的

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 => {
      // 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 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
  }
}

18
投票

您可以使用辅助函数干净地完成此操作:

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

这会抛出一个错误,因此如果您愿意,您可以

catch
它。


1
投票

Fetch
返回一个Promise。有了 Promise 链,像这样的单行就可以了。

const res = await fetch(url, opts).then(r => r.clone().json().catch(() => r.text()));


0
投票

使用 JSON 解析器,如 JSON.parse:

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

0
投票

我决定用这个

   return fetch(url).then(async k =>{
             const res = await k.text();
             if(!res.startsWith("[")) return [];
             return JSON.parse(res);
            }).then(g => {          
          ////
        }) 
       

-1
投票

我最近发布了一个

npm
package,其中包含常见的实用函数。 我在那里实现的功能之一就像 nis
async/await
答案一样,您可以使用如下:

import {fetchJsonRes, combineURLs} from "onstage-js-utilities";

fetch(combineURLs(HOST, "users"))
    .then(fetchJsonRes)
    .then(json => {
        // json data
    })
    .catch(err => {
        // when the data is not json
    })

您可以在Github

上找到源代码
© www.soinside.com 2019 - 2024. All rights reserved.