Json
From GMod Wiki
Json Information Guide |
Description: | A short informative guide to using Json within your scripts. |
Original Author: | Kingzy |
Created: | 11/19/2010 |
Contents |
What is Json?
Json (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.
Json is suitable for encoding and decoding data which may be used in scenarios such as parsing data through a database query.
If you know what glon is, Json is at your advantage if you wish to create human-readable encoded data.
Why use Json?
If - for example you wished to store your player data within a database and your player data was of a table structure, encoding your data would make this task much easier. Json (as mentioned above) is human-readable, which means if it were passed to a database, further editing could be done outwith Lua.
An alternative for encoding data is Glon but should be used for internal use only - such as sending data between the server and client.
Using Json
Below is an example of usage of Json.
local t = { ["name1"] = "value1", ["name2"] = {1, false, true, 23.54, "a \021 string"}, name3 = Json.Null() } local json = Json.Encode (t) print (json) --> {"name1":"value1","name3":null,"name2":[1,false,true,23.54,"a \u0015 string"]} local t = Json.Decode(json) print(t.name2[4]) --> 23.54
Note: While JSON is included in GMod, you will have to use the require function to enable it.
Here is a scenario in which Json may be used in a gamemode:
-- Called when a save query should be retrieved function getSaveQuery(player) return Json.Encode(player.data) end -- Called when a player disconnects and should save function savePlayer(player) sql.Query( "UPDATE tbl_Players SET data = "..getSaveQuery(player).." WHERE SteamID = "..player:SteamID() ) -- (Not sure if this will work *UNTESTED*) end -- Called when a player should load function loadPlayer(player) local results = sql.Query( "SELECT * FROM tbl_Players WHERE SteamID = "..player:SteamID() ) player.data = Json.Decode(results) end hook.Add("PlayerDisconnect", "EncodeData", savePlayer) hook.Add("PlayerInitialSpawn", "DecodeData", loadPlayer)
Additional Notes
- Json allows for the following classes/datatypes to be used:
- String
- Number
- Boolean
- Table
- Nil
- If you wish to insert an 'empty' value use:
Json.Null
- The contents of this article may not be entirely correct and requires redraft.