3

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!

Noon
  • 45
  • 5
  • 2
    `var board = gameContent[0].board;` – Pranav C Balan May 01 '19 at 17:11
  • 2
    ^^ your outermost layer is an array with one object in it. So to access the object, you need `gameContent[0]`. – T.J. Crowder May 01 '19 at 17:12
  • 3
    Separately: This has nothing to do with JSON. You've parsed the JSON, so now you're dealing with JavaScript objects. JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. :-) – T.J. Crowder May 01 '19 at 17:13
  • Alternatively, you can modify the code that outputs the file so that it contains a single object instead of an array. – Code-Apprentice May 01 '19 at 17:16

1 Answers1

3

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;
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73