简体   繁体   中英

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.

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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