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
5 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!

01local DataStore = game:GetService("DataStoreService"):GetDataStore("TestV2")
02local HttpService = game:GetService("HttpService");
03 
04local PlayerData = {}
05local StarterPlayerData = { ['Coins'] = 12312313, ['Diamonds'] = 0, ['Codes'] = 0, ['Kills'] = 0}
06 
07game.Players.PlayerAdded:Connect(function(plr)
08 
09    local key = "user_"..plr.UserId
10 
11    if DataStore:GetAsync(key) == nil then
12        PlayerData[plr] = StarterPlayerData
13    else
14        PlayerData[plr] = HttpService:JSONDecode(DataStore:GetAsync(key));
15    end
View all 26 lines...

2 answers

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

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

1print(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 — 5y
Ad
Log in to vote
0
Answered by
gskw 1046 Moderation Voter
5 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:

1local val = 12312313
2local encoded = HttpService:JSONEncode({val})
3local decoded = HttpService:JSONDecode(encoded)[1]
4print(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 — 5y
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 — 5y

Answer this question