What's the best way or how to store an array in DataStore?

Soo i’m trying to save an inventory data and i need all the items on the player’s invetory to be saved
that’s why i want to save an array, ik that i need to use JSONEncode but idk how to use this properlly

   local datastore = game:GetService("DataStoreService")

    local IventoryData = datastore:GetDataStore("PlayerInventory")

    local Items


    game.Players.PlayerAdded:Connect(function(player)
    	
    	local PlayerId = player.UserId
    	
    	
    	local Folder = Instance.new("Folder", player)
    	Folder.Name = "Iventory"
    	
    	local PlayerHasItemsOnInventory, PlayerItemsOnInventory = pcall(function()
    		
    	return	IventoryData:GetAsync(PlayerId)
    		
    	end)
    	
    	if PlayerHasItemsOnInventory  then
    		
    		if not PlayerItemsOnInventory then
    		PlayerItemsOnInventory = {}
    		end
    		
    		for i, v in ipairs(PlayerItemsOnInventory) do
    			
    			local Item = Instance.new("StringValue", Folder)
    			Item.Name = v
    			
    		end
    		
    	end
    	
    	
    	local function UpdatePlayerDataWithCurrentInventory()
    	
    	Folder.ChildAdded:connect(function()
    		
    		Items = Folder:GetChildren() -- Handle All items on the players folder in one variable every time the event fires
    			
    			

    			local function SavePlayerIventoryData()
               
    				IventoryData:SetAsync(PlayerId, Items)


    			end

    			spawn(SavePlayerIventoryData)	
    							
    		end)
    	
    	
    	end
    	
    	
    	spawn(UpdatePlayerDataWithCurrentInventory)
    end)

DataScriptOutput

1 Like

I am pretty sure you cannot save instances to data stores like that. If you want to save instances and information about instances, you would have to use serialization. @starmaq explains exactly what you are trying to do perfectly here: How to save parts, and the idea of Serialization

If you are trying to save the values of String Values you could simply do a recursive loop like so:

local toSave = {}
local Items = Folder:GetChildren() 

for InventorySlot, StringValue in pairs(Items) do
    toSave[InventorySlot] = StringValue.Value
end

InventoryData:SetAsync(PlayerId, toSave)

Retrieving data would be contrariwise

 for InventorySlot, Value in pairs(PlayerItemsOnInventory) do
     local Item = Instance.new("StringValue")
     Item.Name = Slot..InventorySlot
     Item.Value = Value
     Item.Parent = Folder
 end
1 Like