Defold Learn logo


JSON API documentation

Manipulation of JSON data strings.

Version: alpha

RECORDS
json.decode_options JSON decoding options
json.encode_options JSON encoding options
FUNCTIONS
json.decode() decode JSON from a string to a lua-table
json.encode() encode a lua table to a JSON string
CONSTANTS
json.null null

Records

json.decode_options

JSON decoding options

FIELDS

[decode_null_as_userdata] boolean Decode JSON null as json.null instead of nil.

json.encode_options

JSON encoding options

FIELDS

[encode_empty_table_as_object] boolean Encode an empty table as an object instead of an array. The default is true.

Functions

json.decode()

json.decode(json:string, [options:json.decode_options])→data:any

Decode a string of JSON data into a Lua table. A Lua error is raised for syntax errors.

PARAMETERS

json string
json data
[options] json.decode_options
optional decoding options

RETURNS

data any
decoded JSON value

EXAMPLES

Converting a string containing JSON data into a Lua table:
function init(self)
    local jsonstring = '{"persons":[{"name":"John Doe"},{"name":"Darth Vader"}]}'
    local data = json.decode(jsonstring)
    pprint(data)
end
Results in the following printout:
{
  persons = {
    1 = {
      name = John Doe,
    }
    2 = {
      name = Darth Vader,
    }
  }
}

json.encode()

json.encode(tbl:any, [options:json.encode_options])→json:string

Encode a lua table to a JSON string. A Lua error is raised for syntax errors.

PARAMETERS

tbl any
Lua value to encode
[options] json.encode_options
optional encoding options

RETURNS

json string
encoded json

EXAMPLES

Convert a lua table to a JSON string:
function init(self)
     local tbl = {
          persons = {
               { name = "John Doe"},
               { name = "Darth Vader"}
          }
     }
     local jsonstring = json.encode(tbl)
     pprint(jsonstring)
end
Results in the following printout:
{"persons":[{"name":"John Doe"},{"name":"Darth Vader"}]}

Constants

json.null

Represents the null primitive from a json file