pSash
pSash

Reputation: 25

JSON.stringify does not represent Object which was Stringified

I am working on a Connect Four app for a school project. Currently, I am trying to JSON.stringify an object containing a two-dimensional array of "hole" objects (each containing keys: x, y, column, row, p1, and p2) so that I can send it to the server, and have it broadcast it two clients -> This will keep the game state updated for both clients.

Right before I JSON.stringify(holeObjArray), I console.logged the contents of the object and they show the updated game state:

object before stringify

I've highlighted (in red): holeObjArray[5][6] contains a key 'p1' = 1, and this corresponds to the current game state (on the right).

When I JSON.stringify the object, seen here:

function sendGrid()
{
  console.log(holeObjArray);
  JSONStr = JSON.stringify(holeObjArray);
  console.log(JSONStr);
  //ws.send(JSONStr);
}

The output of JSONStr shows the following:

object after stringify

As you can see, the stringified object does not represent the current game state. In fact, if I continue playing, the stringified object will always represent the state of the board on the last play. I don't understand why JSON.stringify() does this? Especially because the holeObjArray correctly represents the grid before I stringify it, but once I do, the JSONStr string represents the grid on the move before the one that was just made. Any help with this issue would be greatly appreciated,

Thanks,

Alex

Upvotes: 1

Views: 1529

Answers (2)

Greg Hornby
Greg Hornby

Reputation: 7808

In the console, when you expand an object, it shows the values of the object properties at the moment you expand it, not when you logged it to the console. So the JSON.stringify way of logging an object is the correct way of showing the current values at the time you logged it.

Upvotes: 2

Luke Vance
Luke Vance

Reputation: 11

Ok, I apologize for this not being complete. But I think I at least know where you can start.

As I'm sure you know, Javascript has a funny way of handling scope, and so can sometimes generate a seemingly unpredictable state. My hunch is that in this case, the JSON.stringify() method is being hoisted and so is assigning a string to your JSONStr variable sooner than you'd like.

Try something like this instead:

const sendGrid = function(wholeObjArray) {
  console.log(holeObjArray);
  let JSONStr = JSON.stringify(wholeObjArray);
  return JSONStr;
}
// where gamestate === wholeObjArray
console.log(sendGrid(gameState));
ws.send(sendGrid(gameState));

This should ensure that you are not stringifying the JSON object until you actually want to.

Let me know if that helps!

Upvotes: 0

Related Questions