Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a two-dimensional array from JSON [duplicate]

As part of a project to create a simple implementation of Tic Tac Toe, I have created a JSON file to store game information. The file looks something like this:

[
  {
    "turn": "x",
    "board": [
      [
        "🔲",
        "🔲",
        "🔲"
      ],
      [
        "🔲",
        "🔲",
        "🔲"
      ],
      [
        "🔲",
        "🔲",
        "🔲"
      ]
    ],
    "victory": false,
    "date": 1556727248491
  }
]

To access a session, the two-dimensional array would be iterated over and then output. When printing into the console it correctly outputs the entire object, looking something like this:

[ { turn: 'x',
    board: [ [Array], [Array], [Array] ],
    victory: false,
    date: 1556729502590 } ]

However, when I try to access the array (board), it returns as undefined. Here is an example of the code I am trying to use to access this array (of arrays).

let gameObject = fs.readFileSync("filename.json");
let gameContent = JSON.parse(gameObject);
var board = gameContent.board;

I am rather uncertain of what I am doing wrong here, as I do not have a lot of experience with accessing JSON files, any help would be appreciated!


1 Answers

gameContent is an array and its first element have property board. So access its first element and then access board.

var board = gameContent[0].board;
like image 56
Maheer Ali Avatar answered Feb 04 '26 02:02

Maheer Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!