How Would I Store A Folder In A DataStore?

So I’m trying to store my “Hats” for my hat inventory, I tried a lot of different stuff but none of them worked, it always gives me an error, or it doesn’t work?

What I’m trying to store:
image

I’ve tried using JSONEncode and JSONDecode but it hasn’t worked for me, it gives me a null value instead of the actual value.

Serverscript:

local DS = game:GetService("DataStoreService")
local PlrService = game:GetService("Players")


local function onPlayerRemoving(plr)
	
	wait()
	
	local Datastore = game:GetService("DataStoreService"):GetDataStore(plr.Name.."tHats01")
	
	local Data = {}
	
	for _, ValuesToSave in pairs(plr:WaitForChild("Inventory").Hats:GetChildren()) do
		
		game:GetService("HttpService"):JSONEncode(ValuesToSave)
		
		table.insert(Data, ValuesToSave)
	end
	
	if Data ~= nil then
		
		Datastore:SetAsync(plr.UserId, game:GetService("HttpService"):JSONEncode(Data))
		
	else
		
		print("No assets to save for " .. tostring(plr.Name) .. ".")
		
	end

end

PlrService.PlayerRemoving:Connect(onPlayerRemoving)

local function onPlayerAdded(plr)
	
	local Datastore = game:GetService("DataStoreService"):GetDataStore(plr.Name.."tHats01")
	
	local SavedFiles = Datastore:GetAsync(plr.UserId)
	
	local ActualFile = game:GetService("HttpService"):JSONDecode(SavedFiles)

	if ActualFile ~= nil then
		
		warn("Data Loading")
		
		
		for _, LoadValues in pairs(ActualFile) do
			
			end
			
	else
		
		warn("File Empty")
		
	
	end
	
	
end

PlrService.PlayerAdded:Connect(onPlayerAdded)

game:BindToClose(function()

	wait(10)
	
end)

Any ideas why it won’t work?

1 Like

You cannot save instances in datastores. You need to create a method of serializing your folder into a format that can be saved. Something like:

...
["Hats"] = {
	["Blue Swoosh Hair"] = {
		["Color"] = (value),
		["ImageID"] = (value),
		["Rarity"] = (value)
	},
	...
},
...

Also, you don’t need to encode your tables into JSON format to save in a datastore, it is done automatically. You were probably getting errors from trying to encode instances.

3 Likes