Saving data with JSON: Unable to cast value to std::string

so basically im trying to encode the data with JSON, save it and then load it and decode with JSON but i get this error:
image]

local datastore2 = require(1936396537)
datastore2.Combine("DATA","Values")
local HTTP = game:GetService("HttpService")

game.Players.PlayerAdded:Connect(function(plr)
	local valds = datastore2("Values",plr)
	local ls = plr:WaitForChild("leaderstats")
	local coinsVal = ls:WaitForChild("Coins")
	local xpVal = ls:WaitForChild("XP")
	local values = HTTP:JSONDecode(valds:Get())
	if values ~= nil then
		coinsVal.Value = values.Coins
		xpVal.Value = values.XP
	else
		coinsVal.Value = 1
		xpVal.Value = 1
	end	
end)

game.Players.PlayerRemoving:Connect(function(plr)
	local valds = datastore2("Values",plr)
	local valtable = {}
	valtable.Coins = plr.leaderstats.Coins.Value
	valtable.XP = plr.leaderstats.XP.Value
	local DataToSave = HTTP:JSONEncode(valtable)
	valds:Set(DataToSave)
end)

You don’t have to use JSON Encode/Decode for datastore it’s automatically converted in the backend.

Just don’t use it and you’ll have no errors.

yeah but im just testing it so i can use it for my other game where i have to save literally thousands of tables

As mentioned, what you pass is automatically encoded to JSON for you, you don’t need to do anything on your end. Encoding it yourself doesn’t allow you to save more – in fact quite the contrary. If you encode it yourself, the data ends up being encoded again, so that means there are more backslashes and double quotes taking up valuable space.

1 Like

does normal datastore do that too or is it only datastore2

DataStore2 uses normal data stores (literally every data store module does), so anything data stores do in the backend, DataStore2 does as well, since DataStore2 is quite literally a wrapper around Roblox’s data stores.

i mean is it only datastore2 that automatically does json encoding and decoding or does the normal one do it too.
yeah ii know it uses the normal datastore but perhaps there is a function in the module that automatically encodes to json

As I have said, data stores do that automatically for you. When you :SetAsync/:UpdateAsync, the data is already encoded into JSON. When you :GetAsync the data is decoded from JSON.

someone just told me that i should save big tables with json and now im told to not do that, im kinda confused

You already save tables using JSON. Roblox does all that for you. No need to do it yourself.

so is there anything i could to to make the data more secure now? once i am using datastore 2 and autosaving

DataStore2 seems to do that automatically, so I don’t believe so

well, thanks for help i guess i have already pushed the odds of data loss as low as i possibly could.