JsonService
Turn a table into JSON text and back, for settings files, web answers and anything another program reads.
Neither call waits. Encode sorts keys, writes a table with keys 1 to n as an array and any other table as an object with string keys, and with pretty indents by two spaces. A value JSON can't hold is a mistake in the code, so Encode errors; bad text comes from outside, so Decode gives nil and why.
A service: write use JsonService.
Example
-- Turns a to-do list into JSON text and back; keys come out sorted.
use JsonService
local todo = { Title = "Notes", Items = { "buy milk", "call home" }, Done = false }
local text = JsonService:Encode(todo)
print(text)
print(JsonService:Encode({ Count = 2, Done = true }, true))
local back = JsonService:Decode(text)
print("decoded: " .. back.Title .. ", " .. #back.Items .. " items")
print("a table with a gap is an object: " .. JsonService:Encode({ [1] = "a", [3] = "c" }))
local bad, why = JsonService:Decode("{ not json")
print("bad text: " .. tostring(bad) .. ", " .. tostring(why)){"Done":false,"Items":["buy milk","call home"],"Title":"Notes"}
{
"Count": 2,
"Done": true
}
decoded: Notes, 2 items
a table with a gap is an object: {"1":"a","3":"c"}
bad text: nil, Decode: key must be a string at line 1 column 3Methods
| Name | Arguments | Returns | Description |
|---|---|---|---|
| Decode | (text: string) | (any, string?) | The value of JSON text, without waiting, JSON null becoming nil; bad text gives nil and why instead of an error. |
| Encode | (value: any, pretty: boolean?) | string | JSON text with keys sorted; tables with keys 1 to n are arrays, others objects, and a function or a cycle errors. |
From ShotInstance 33
ClassNameNameParentAncestryChangedAttributeChangedChangedChildAddedChildRemovedDestroyingAddTagClearAllChildrenCloneDestroyFindFirstAncestorFindFirstAncestorOfClassFindFirstAncestorWhichIsAFindFirstChildFindFirstChildOfClassFindFirstChildWhichIsAGetAttributeGetAttributeChangedSignalGetAttributesGetChildrenGetDescendantsGetFullNameGetPropertyChangedSignalGetTagsHasTagIsAIsAncestorOfIsDescendantOfRemoveTagSetAttribute
