Defold
json
Manipulation of JSON data strings.
Functions
json.decode(json: string, options?: { decode_null_as_userdata?: boolean }): Record<string | number, unknown>
- Signature changed in Defold 1.13.2
Decode a string of JSON data into a Lua table. A Lua error is raised for syntax errors.
Converting a string containing JSON data into a Lua table:
export default defineScript({
init() {
const jsonstring = '{"persons":[{"name":"John Doe"},{"name":"Darth Vader"}]}';
const data = json.decode(jsonstring);
pprint(data);
},
});function init(self)
local jsonstring = '{"persons":[{"name":"John Doe"},{"name":"Darth Vader"}]}'
local data = json.decode(jsonstring)
pprint(data)
endResults in the following printout:
// {
// persons = {
// 1 = {
// name = John Doe,
// }
// 2 = {
// name = Darth Vader,
// }
// }
// }{
persons = {
1 = {
name = John Doe,
}
2 = {
name = Darth Vader,
}
}
}Parameters
json:string— json dataoptions?:{ decode_null_as_userdata?: boolean }— table with decode options- boolean
decode_null_as_userdata: whether to decode a JSON null value as json.null or nil (default is nil)
- boolean
Returns
data:Record<string | number, unknown>— decoded json
json.encode(tbl: PlainTable, options?: { encode_empty_table_as_object?: string }): string
- Signature changed in Defold 1.13.2
Encode a lua table to a JSON string. A Lua error is raised for syntax errors.
Convert a lua table to a JSON string:
export default defineScript({
init() {
const tbl = {
persons: [{ name: "John Doe" }, { name: "Darth Vader" }],
};
const jsonstring = json.encode(tbl);
pprint(jsonstring);
},
});function init(self)
local tbl = {
persons = {
{ name = "John Doe"},
{ name = "Darth Vader"}
}
}
local jsonstring = json.encode(tbl)
pprint(jsonstring)
endResults in the following printout:
// {"persons":[{"name":"John Doe"},{"name":"Darth Vader"}]}{"persons":[{"name":"John Doe"},{"name":"Darth Vader"}]}Parameters
tbl:PlainTable— lua table to encodeoptions?:{ encode_empty_table_as_object?: string }— table with encode options- string
encode_empty_table_as_object: whether to encode an empty table as an JSON object or array (default is object)
- string
Returns
json:string— encoded json
Variables
json.null: unknown
Represents the null primitive from a json file