Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Datastore, JSON cant be converted?

I had this code for awhile now, but on line 16 I cant convert to json? I try using other things inside the table, just making sure it wasnt coins, but it's on all. how do I fix? what am I doing wrong, thanks!

local DataStore = game:GetService("DataStoreService"):GetDataStore("TestV2")
local HttpService = game:GetService("HttpService");

local PlayerData = {}
local StarterPlayerData = { ['Coins'] = 12312313, ['Diamonds'] = 0, ['Codes'] = 0, ['Kills'] = 0}

game.Players.PlayerAdded:Connect(function(plr)
	
	local key = "user_"..plr.UserId
	
	if DataStore:GetAsync(key) == nil then
		PlayerData[plr] = StarterPlayerData
	else
		PlayerData[plr] = HttpService:JSONDecode(DataStore:GetAsync(key));
	end
	print(HttpService:JSONEncode(PlayerData[plr]['Coins']))
end)

game.Players.PlayerRemoving:Connect(function(plr)
	local key = "user_"..plr.UserId
	
	if PlayerData[plr] == nil then
		DataStore:SetAsync(key, HttpService:JSONEncode(PlayerData[plr]))
	end
	
end)

2 answers

✓ Accepted answer

Because you cannot convert something that is already converted. So instead your code should be:

print(HttpService:JSONEncode(PlayerData[plr]))

This will encode the entire table, and print the table data instead of just printing one value. Hope this works!

1 comment

0

This works thanks!

It appears that JSONEncode only accepts table values. For all other types, it errors with either Argument 1 missing or nil or Can't convert to JSON. In my personal opinion, this is something that could be improved upon in the Roblox API. According to json.org, standalone number, boolean and string literals are all valid JSON.

Where to go from here? It depends on what your goal is. If you need to use JSONEncode to store a single numerical value, you can wrap it up in a table:

local val = 12312313
local encoded = HttpService:JSONEncode({val})
local decoded = HttpService:JSONDecode(encoded)[1]
print(val) --> 12312313

If you're storing the numerical value as a part of table (as is evident from your PlayerRemoving code), then that part of your code doesn't have any issues. It seems to me that the only issue here is the code in the print argument, though I couldn't say for sure without additional information.

2 comments

0

so like you created the variable 'val' I can still get a single value in the table if var.Val is inside?

0

Assuming I understood your question correctly, then yes. You can't convert a single value to JSON (other than tables), unless it's stored in a table. That is what is done in my code, though it probably isn't useful for your script.

This discussion is preserved as it was. New answers, comments, and votes are closed.