Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Datastore, JSON cant be converted?

Asked by
Code1ng 15
4 years ago

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

Log in to vote
0
Answered by
B_rnz 171
4 years ago

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!

0
This works thanks! Code1ng 15 — 4y
Ad
Log in to vote
0
Answered by
gskw 1046 Moderation Voter
4 years ago

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.

0
so like you created the variable 'val' I can still get a single value in the table if var.Val is inside? Code1ng 15 — 4y
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. gskw 1046 — 4y

Answer this question