简体   繁体   English

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

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

I am constructing a web application which uses a Go server to serve data to a React app.我正在构建一个 web 应用程序,它使用 Go 服务器向 React 应用程序提供数据。

In the construction of my server, I followed the tutorial provided by Go docs ( https://golang.org/doc/tutorial/web-service-gin ).在我的服务器的构建中,我遵循了 Go 文档( https://golang.org/doc/tutorial/web-service-gin )提供的教程。 My code is very similar to that code, and I get the expected results when I use curl .我的代码与该代码非常相似,当我使用curl时,我得到了预期的结果。

[
  {
    "id":0,
    "date":"2021-11-21T12:00:00Z",
    "rentedTo":"Bob",
    "rentedBy":"Jim"
  },
  //etc...

When I use React's fetch API, however, my results come back in an unexpected form.然而,当我使用 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);
});

When I console.log(jsonArr) , the browser reports the following:当我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", ... }

These indices (and the browser's label) indicated that the data was now in the form of an Array, so I treated it as such.这些索引(和浏览器的标签)表明数据现在是数组的形式,所以我就这样对待它。

I attempted to loop through this array to parse the json strings inside of it, but JSON.parse(data) produces only numbers (0, 1, and 2 respectively) rather than producing objects, as I expected it to.我试图遍历这个数组来解析其中的 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.
}

I have done some searching, and have heard that the indices of the array the data came in may be causing an issue, so I tried to parse with a reviver function, as well.我做了一些搜索,听说数据进来的数组的索引可能会导致问题,所以我也尝试使用 reviver function 进行解析。

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
}

Attempting to JSON.parse(jsonArr) throws an error, as expected.正如预期的那样,尝试JSON.parse(jsonArr)会引发错误。 I'm stumped.我难住了。 Why does it parse into a(n index) number?为什么它会解析成一个(n 索引)数字? How can I extract the Objects inside of the Array, when parsing (or printing) the strings inside of the array produces only numbers?当解析(或打印)数组内的字符串只产生数字时,如何提取数组内的对象?

The json value in for (const json in jsonArr) { will be set to the "enumerable properties" of the jsonArr Array, which, in this case, are the indexes. for (const json in jsonArr) {json值将设置为jsonArr数组的“可枚举属性”,在这种情况下,它是索引。

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

So you probably don't want to use for... in .所以你可能不想使用for... in Instead you can use for... of to iterate over the elements of the array:相反,您可以使用for... of来迭代数组的元素:

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

Array iteration and for... in : 数组迭代和for... in

Note: for...in should not be used to iterate over an Array where the index order is important.注意: for...in不应用于迭代索引顺序很重要的数组。

Array indexes are just enumerable properties with integer names and are otherwise identical to general object properties.数组索引只是具有 integer 名称的可枚举属性,在其他方面与一般 object 属性相同。 There is no guarantee that for...in will return the indexes in any particular order.不能保证for...in将按任何特定顺序返回索引。 The for...in loop statement will return all enumerable properties, including those with non–integer names and those that are inherited. for...in循环语句将返回所有可枚举属性,包括具有非整数名称的属性和继承的属性。

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.因此,在访问顺序很重要的 arrays 上迭代时,最好使用带有数字索引的for循环(或Array.prototype.forEach()for...of循环)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM