Search code examples
arraysjsongodotgodot4

How to iterate through an array to convert to JSON


I am running Godot 4 and my ultimate goal is to convert data into JSON in order to save it to a file. I am just not winning on getting the data out of an Array of a custom class.

This is the definition of the class

extends Node

class_name BusinessType

var location = Vector2(0,0)
var appeal : int
var products 
var startDay : int

In Global.gd I have

var businesses : Array[BusinessType] = []

Here is an extract of where I attempt to print it

func save_file():
    var myBus = BusinessType.new()
    var myBusName = "Random Name "
    myBus.name=myBusName
    myBus.appeal=randi_range(0,100)
    Global.businesses.append(myBus)

    var busData_json = JSON.stringify(Global.businesses)
    for i in Global.businesses.size():
        
        print("\n".join(Global.businesses))

I am expecting to see something like

Random Name , location : (0, 0), appeal : 45

I am seeing

Random Name :<Node#31155291392>

I have tried various permutations of commands including

print("\n".join(Global.businesses)) print(Global.businesses[i])

Any ideas welcome for this NOOB


Solution

  • The default behavior of the JSON.stringify method does not know how to convert custom class instances into JSON.

    To do this, you can implement a method within your custom class to convert its properties into a dictionary, which can then be easily converted to JSON.

        extends Node
    
    class_name BusinessType
    
    var location = Vector2(0, 0)
    var appeal : int
    var products = []
    var startDay : int
    
    
    func to_dict() -> Dictionary:
        return {
            "name": name,
            "location": location,
            "appeal": appeal,
            "products": products,
            "startDay": startDay
        }
    extends Node
    
    var businesses : Array[BusinessType] = []
    
    func save_file():
        var myBus = BusinessType.new()
        var myBusName = "Random Name "
        myBus.name = myBusName
        myBus.appeal = randi_range(0, 100)
        Global.businesses.append(myBus)
    
       
        var businesses_dict_array = []
        for business in Global.businesses:
            businesses_dict_array.append(business.to_dict())
    
      
        var busData_json = JSON.stringify(businesses_dict_array)
    
        
        var file = File.new()
        if file.open("res://businesses.json", File.WRITE) == OK:
            file.store_string(busData_json)
            file.close()
    
        
        for business in Global.businesses:
            print(business.to_dict())