Skip to Content
defold-typescript
Get startedGuidesAPILibraries
Defold

json

Manipulation of JSON data strings.

Functions

json.decode(json: string, options?: json.DecodeOptions): unknownC

  • Signature changed in Defold 1.13.2 — before: (json: string, options?: { decode_null_as_userdata?: boolean }): Record<string | number, unknown>

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)
end

Results 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 data
  • options?: json.DecodeOptions — optional decoding options

Returns

  • data: unknown — decoded JSON value

json.encode(tbl: unknown, options?: json.EncodeOptions): stringC

  • Signature changed in Defold 1.13.2 — before: (tbl: PlainTable, options?: { encode_empty_table_as_object?: string })

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)
end

Results in the following printout:

// {"persons":[{"name":"John Doe"},{"name":"Darth Vader"}]}
{"persons":[{"name":"John Doe"},{"name":"Darth Vader"}]}

Parameters

  • tbl: unknown — Lua value to encode
  • options?: json.EncodeOptions — optional encoding options

Returns

  • json: string — encoded json

Variables

json.null: unknown

Represents the null primitive from a json file

Types

interface json.DecodeOptions { decode_null_as_userdata?: boolean; }

interface json.EncodeOptions { encode_empty_table_as_object?: boolean; }

On this page