Json in Lua - Henningstone/HMod GitHub Wiki
Contents
Global Namespace json
The json api is intended as a common interface to store data in. The data is created in lua and can be converted back and forth.
Parse
json.Parse(JsonString)
Parses the given valid json string into a JsonValue object and returns it. This object is used to convert the data (explained in section below). It is important that you call the Destroy method of that object after you are done with it.
Convert
json.Convert(LuaData)
Converts any kind of lua data type thing into a JsonValue object and returns it. Only functions, userdata and lua threads can not be converted.
Serialize
json.Serialize(JsonValue, Shorten)
Serialises a JsonValue object into a valid json string that can be parsed again, written to a file or printed in the console. If Shorten
is true, the resulting json string will be minified.
Read
json.Read(JsonString)
Tries to automatically parse and convert the json string into the appropriate lua data and returns it.
Working with a JsonValue object
JsonValue objects are an intermediate state when converting a json string back to lua data and represent the entire json data at once. A JsonValue is obtained from the parse function:
myJsonValue = json.Parse('[ {"aa": 3, "ab": 5}, { "ba": 7, "bb": "hi"}, "test" ]')
Destroy
myJsonValue:Destroy()
It is important to call this function once you are done with this JsonValue to free up internal resources. Not calling this function causes a memory leak.
GetType
myJsonValue:GetType()
Returns the type of this json value as a string; one of: object
, array
, number
, string
, boolean
, nil
, error
Retrieving lua data
To turn a json value into native lua data, the appropriate conversion method must be used:
myJsonValue:ToString()
myJsonValue:ToNumber()
myJsonValue:ToBoolean()
myJsonValue:ToTable()
myJsonValue:ToObject()