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

JSON Data Persistence

Can anyone tell me how to use jSon in data persistence?

That means saving and loading.

2 answers

✓ Accepted answer

Are you talking about the old player-based data persistence, or the new data stores API?

To encode a table in JSON, use:

local RbxUtility = LoadLibrary("RbxUtility")

tableToEncode = {"Player1", "Player2", "Player3"}
local encoded = RbxUtility.JSONEncode(tableToEncode)

Then to decode it:

local decoded = RbxUtility.JSONDecode(encoded)

If you're using the old player-based data persistence, you would call Player:SaveString(encoded). If you're using data stores, you would have to get a data store object from the DataStoreService, and then call DataStore:SetAsync(key, value) where value is your encoded table.

1 comment

0

Thanks for helping on saving and removing!

JSON basically is a data format, just like for example how Microsoft Word saves its data.

JSON is used by most people to convert tables to strings and those strings back to the original tables.

As you know, the NORMAL data persistence (:SaveString()) can only save strings (or numbers / booleans / instances) but not tables. You can use JSON to convert tables to strings, and save those strings, and then load these strings and convert these back to tables again.

A small example:

local Utility = LoadLibrary "RbxUtility"

local StringToTable = Utility.DecodeJSON
local TableToString = Utility.EncodeJSON

local PlayerStats = {happiness = 30, items = {"banana", "apple"}, cool = true, admin = false}

local Player = game.Players.Player1 -- a test player 
local key = "test_key"

Player:SaveString(key, TableToString(PlayerStats))
-- saved the table PlayerStats
-- now load it
local load = Player:LoadString(key)
local original = StringToTable(load)
print(original.happiness, original.items[2], original.cool)

2 comments

0

Thanks for helping with loading!

0

No problem. You should consider the new data persistence though. This data persistence just accepts tables as data - in fact, it doesn't accept strings or numbers, only tables. It may be handier for you to save things like that. Maybe you should take a look at it : http://wiki.roblox.com/index.php?title=Data_store

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