Hi there, I'm pretty new to Godot & GDScript. I'm trying to output some data in JSON from a GODOT app and I've not had any success without hand building the JSON encoding in strings. So I'm doing this...

	var max_x = map.get_used_rect().end.x+1
	var max_y = map.get_used_rect().end.y+1
	var hexes = "{\"hexes\":{"
	var json_object = JSON.new()
	
	for x in max_x:
		for y in max_y:
			var id = map.get_cell_source_id((0), Vector2i(x,y))
			if id > -1:
				hexes+= "\""+str(x)+str(y)+"\":{"
				hexes+="\"x\":"+str(x)+","
				hexes+="\"y\":"+str(y)+","
				hexes+="\"terrain\":"+str(id)+"},"
	
	hexes += "}}"
	print(hexes)

Which generates {"hexes":{"00":{"x":0,"y":0,"terrain":1},"01":{"x":0,"y":1,"terrain":1},"02":{"x":0,"y":2,"terrain":2},"10":{"x":1,"y":0,"terrain":0},"20":{"x":2,"y":0,"terrain":0},"22":{"x":2,"y":2,"terrain":2},"30":{"x":3,"y":0,"terrain":2},}}
And is basically correct, except for the extra ",".

When I tried to do this by creating a JSON Node object with the terrain, x & y fields and then called to_json() I just get what I suspect is the internal Node reference ID encapsulated in JSON format. Is there a way to auto generate JSON encoding on objects that walks through the fields correctly?

  • SashaBilton If JSON::stringify() encounters an object reference it won't go into listing its properties. You'll have to manually extract and put them into the dictionary.

Thanks for the reply. When I tried that before, the objects I'd added to the dictionary didn't get converted to json and I ended up with node id but not the properties of each object in the dictionary. I'll try this again though as maybe I wasn't adding them correctly.

  • xyz replied to this.

    SashaBilton If JSON::stringify() encounters an object reference it won't go into listing its properties. You'll have to manually extract and put them into the dictionary.

    No, I mean you create a Dictionary with exactly the information you want, and then convert it to JSON.

      cybereality does putting objects into a Dictionary mean they'll automatically get JSONified when you stringify() the dictionary?

      Would

      extends Node
      class_name Hex
      
      var terrain : int
      var x : int
      var y : int

      automatically get converted to {"terrain": , "x":, "y": } or do I need to still do that myself? Thanks for the help!

      • xyz replied to this.

        SashaBilton No. You'll have to do it yourself. Best to implement a class method that'll return a dictionary of all class properties you need to serialize.