How do I load a JSON array that's inside an array?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By CM333

So, I want to load random level data using json files rather than try and figure out completely in engine level generation. Problem is that I’m relatively new to GDScript (and programming in general) and don’t know much about JSON compatibility. My level file JSONs look like this:

testRoom1.json

{
  "ogmoVersion": "3.4.0",
  "width": 80,
  "height": 60,
  "offsetX": 0,
  "offsetY": 0,
  "layers": [
    {
      "name": "collision",
      "_eid": "02443013",
      "offsetX": 0,
      "offsetY": 0,
      "gridCellWidth": 20,
      "gridCellHeight": 20,
      "gridCellsX": 4,
      "gridCellsY": 3,
      "tileset": "Placeholder Tiles",
      "data": [-1, -1, -1, -1, 2, -1, -1, 2, -1, -1, -1, -1],
      "exportMode": 0,
      "arrayMode": 0
    }
  ]
}

And the GDScript I have right now is a bit like this:

levelGen.gd

extends TileMap

func _ready():
	var toPrint = _grabTileArray()
	print_debug(toPrint)

func _grabTileArray():
	var data_file = File.new()
	if data_file.open("res://roomData/testRoom1.json", File.READ) != OK:
		return null
	var data_text = data_file.get_as_text()
	data_file.close()
	var data_parse = JSON.parse(data_text)
	if data_parse.error != OK:
		return
	var data = data_parse.result
	var tileArray = data["layers"]["data"]
	return tileArray

Any help would be appreciated.

:bust_in_silhouette: Reply From: USBashka

Since thedata array not direct child of layers but the element of list, you need to write

var tileArray = data["layers"][0]["data"]

This way you’re getting data of 0 (first) element of layers of .json-file.

Thanks for the help!

CM333 | 2022-07-29 16:29

:bust_in_silhouette: Reply From: scrubswithnosleeves

There is really no point in using a JSON unless you intend on sharing the file with other applications. Just make a new script and put

class_name = LevelInfo #or whatever you want to call it

const levels := {
"level1" : {ALL THE INFO}

Then you can access the info from any script by doing LevelInfo.levels.get(“level1”)