从 Go/Golang 服务器获取的数据以意外的 JSON 格式解析为数字

React fetch from Go/Golang server parsing data in unexpected JSON format to number

我正在构建一个 Web 应用程序,它使用 Go 服务器向 React 应用程序提供数据。

在构建我的服务器时,我遵循了Go docs (https://golang.org/doc/tutorial/web-service-gin)提供的教程。我的代码与那个代码非常相似,当我使用 curl.

时我得到了预期的结果
[
  {
    "id":0,
    "date":"2021-11-21T12:00:00Z",
    "rentedTo":"Bob",
    "rentedBy":"Jim"
  },
  //etc...

然而,当我使用 React 的 fetch API 时,我的结果以一种意想不到的形式返回。

fetch('http://localhost:8080/rentals')
.then((response)=> {
  if (response.ok) {
    return response.json();
  }
  throw response;
.then((jsonArr) => {
  handleRentalsData(jsonArr)
  })
.catch((error) => {
  console.error("Error fetching data: ", error);
});

当我console.log(jsonArr)时,浏览器报告如下:

Array(3) [ {...},{...},{...} ]
//Expanding this object via the console shows the following information:
---> 0: Object { id: 0, date: "2021-11-21T12:00:00Z", rentedTo: "Bob", ... } 
---> 1: Object { id: 1, date: "2021-11-22T12:00:00Z", rentedTo: "Bob", ... }
---> 2: Object { id: 2, date: "2021-11-23T12:00:00Z", rentedTo: "Bob", ... }

这些索引(和浏览器的标签)表明数据现在是数组形式,所以我这样处理它。

我试图遍历这个数组来解析其中的 json 字符串,但是 JSON.parse(data) 只生成数字(分别为 0、1 和 2)而不是生成对象,因为我期待它。

for (const json in jsonArr){
  console.log(typeof json);            //string
  const rentalObj = JSON.parse(json);
  console.log(typeof rentalObj);       //number
  console.log(rentalObj);              //0, 1, and 2 respectively
  console.log(rentalObj.date);         //undefined, because rentalObj is now a number.
}

我做了一些搜索,听说数据传入的数组的索引可能会导致问题,所以我也尝试使用 reviver 函数进行解析。

for (const json in jsonArr){
  console.log(typeof json);            //string
  const rentalObj = JSON.parse(json, (key, value) => {
    console.log(key);                  //<empty string>
    console.log(value);                //0, 1, and 2
    return(value);
  });
  console.log(typeof rentalObj);       //number
  console.log(rentalObj);              //0, 1, and 2 respectively
  console.log(rentalObj.date);         //undefined
}

尝试 JSON.parse(jsonArr) 会按预期抛出错误。我很难过。为什么它解析成一个(n 索引)数字?当解析(或打印)数组中的字符串只产生数字时,如何提取数组中的对象?

for (const json in jsonArr) { 中的 json 值将被设置为 jsonArr 数组的“可枚举属性”,在本例中为索引。

for (const x in ['foo','bar','baz']) { console.log(x) };
// output:
// 0
// 1
// 2

所以您可能不想使用 for ... in。相反,您可以使用 for ... of 遍历数组的元素:

for (const x of ['foo','bar','baz']) { console.log(x) };
// output:
// foo
// bar
// baz

Array iteration and for ... in:

Note: for...in should not be used to iterate over an Array where the index order is important.

Array indexes are just enumerable properties with integer names and are otherwise identical to general object properties. There is no guarantee that for...in will return the indexes in any particular order. The for...in loop statement will return all enumerable properties, including those with non–integer names and those that are inherited.

Because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order. Therefore, it is better to use a for loop with a numeric index (or Array.prototype.forEach() or the for...of loop) when iterating over arrays where the order of access is important.