Can someone help me figure out how to serialize this data?

function serializeFolder(folder: Folder)
	local result = {}
	
	for _, object in folder:GetChildren() do
		if object:IsA('ValueBase') then --the class of value objects
			
			--necessary as datastore can only save bool,string,number
			local isValueSavable = type(object.Value) ~= 'userdata'
			result[object.Name] = 
				if isValueSavable then object.Value else tostring(object.Value)
			
		
		elseif object:IsA('Folder') then
			result[object.Name] = serializeFolder(object)
		end
	end
	
	return result
end

it would give you this result:

print(serializeFolder(workspace["Save Slot #1"]))
--[[
{
   ["ControlSeat"] =  ▼  {
      ["Cframe"] = "0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1",
      ["Keybinds"] =  ▼  {
         ["Light"] =  ▼  {
            ["Activate"] = "keybind",
            ["Light"] = "keybind"
         }
      },
      ["Settings"] =  ▼  {
         ["Anchored"] = false,
         ["BoatControl"] = false,
         ["CanCollide"] = false,
         ["Transparency"] = 0
      },
      ["blockId"] = 0
   },
   ["Light"] =  ▼  {
      ["Cframe"] = "0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1",
      ["Settings"] =  ▼  {
         ["Anchored"] = false,
         ["CanCollide"] = false,
         ["Transparency"] = 0
      },
      ["blockId"] = 0,
   },
   ["WoodPlanks"] =  ▼  {
      ["Cframe"] = "0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1",
      ["Settings"] =  ▼  {
         ["Anchored"] = false,
         ["CanCollide"] = false,
         ["Transparency"] = 0
      },
      ["blockId"] = 0,
   }
}
]]

must note that this specific example ^ has a problem
It doesn’t work if children share the same name, as it would overwrite the previous key in the dictionary.

which could be solved by saving children as an array rather than a dictionary, but then you must save extra data related to the name of the instance, the classtype, etc.

I would recommend looking into a serialization library if you can’t come up with a structure that would make it easy for you to reconstruct the objects back from

like this one:

1 Like