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

huangapple go评论102阅读模式
英文:

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

问题

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

在构建服务器时,我按照Go文档提供的教程(https://golang.org/doc/tutorial/web-service-gin)进行操作。我的代码与该代码非常相似,并且在使用curl时获得了预期的结果。

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

然而,当我使用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) [ {...},{...},{...} ]
//通过控制台展开此对象,显示以下信息:
---> 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和2
  console.log(rentalObj.date);         //因为rentalObj现在是一个数字,所以为undefined。
}

我进行了一些搜索,并听说数组中的索引可能会导致问题,因此我尝试使用一个reviver函数进行解析。

for (const json in jsonArr){
  console.log(typeof json);            //string
  const rentalObj = JSON.parse(json, (key, value) => {
    console.log(key);                  //空字符串
    console.log(value);                //0、1和2
    return(value);
  });
  console.log(typeof rentalObj);       //number
  console.log(rentalObj);              //分别为0、1和2
  console.log(rentalObj.date);         //undefined
}

尝试JSON.parse(jsonArr)会抛出错误,这是预期的。我被难住了。为什么它解析为(索引)数字?当解析(或打印)数组中的字符串只产生数字时,我如何提取数组内部的对象?

英文:

I am constructing a web application which uses a Go server to serve data to a React app.

In the construction of my server, I followed the tutorial provided by Go docs (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.

[
  {
    "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.

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:

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.

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.

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. I'm stumped. Why does it parse into a(n index) number? How can I extract the Objects inside of the Array, when parsing (or printing) the strings inside of the array produces only numbers?

答案1

得分: 1

for (const json in jsonArr) {中,json的值将被设置为jsonArr数组的“可枚举属性”,在这种情况下,即为索引。

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

因此,你可能不想使用for ... in。相反,你可以使用for ... of来迭代数组的元素:

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

数组迭代和for ... in

> **注意:**不应该使用for...in来迭代顺序很重要的数组。
>
> 数组索引只是具有整数名称的可枚举属性,与一般对象属性完全相同。不能保证for...in会按照特定顺序返回索引。for...in循环语句将返回所有可枚举属性,包括那些具有非整数名称和继承的属性。
>
> 由于迭代顺序是依赖于实现的,因此在迭代数组时可能无法以一致的顺序访问元素。因此,最好使用带有数值索引的for循环(或Array.prototype.forEach()for...of循环),以确保访问顺序的一致性。

英文:

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 x in ['foo','bar','baz']) { console.log(x) };
// output:
// 0
// 1
// 2

So you probably don't want to use for ... in. Instead you can use for ... of to iterate over the elements of the array:

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.

huangapple
  • 本文由 发表于 2021年11月23日 12:47:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/70075530.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定