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)
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!
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.