Log in to vote

JSON Data Persistence

Asked by
Bloxks 30
7 years ago

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

That means saving and loading.

2 answers

Log in to vote
Answered by
Merely 2117 Moderation Voter Community Moderator
7 years ago

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.

Thanks for helping on saving and removing! Bloxks 30 — 7y
Log in to vote
Answered by
jobro13 980 Moderation Voter
7 years ago

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],
Thanks for helping with loading! Bloxks 30 — 7y
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 : jobro13 980 — 7y

Answer this question