On this page

json

Manipulation of JSON data strings.

Functions

json.decode(json: string, options?: Record<string | number, unknown>): 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 table:
export default defineScript({
  init() {
    const jsonstring = '{"persons":[{"name":"John Doe"},{"name":"Darth Vader"}]}';
    const data = json.decode(jsonstring);
    pprint(data);
  },
});

// Results in the following printout:
// {
//   persons = {
//     1 = {
//       name = John Doe,
//     }
//     2 = {
//       name = Darth Vader,
//     }
//   }
// }

Parameters

  • json: string — json data

  • options?: Record<string | number, unknown> — table with decode options

  • boolean decode_null_as_userdata: wether to decode a JSON null value as json.null or nil (default is nil)

Returns

  • data: Record<string | number, unknown> — decoded json

json.encode(tbl: Record<string | number, unknown>, options?: Record<string | number, unknown>): string

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

// Convert a 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);
  },
});

// Results in the following printout:
// {"persons":[{"name":"John Doe"},{"name":"Darth Vader"}]}

Parameters

  • tbl: Record<string | number, unknown> — lua table to encode

  • options?: Record<string | number, unknown> — table with encode options

  • string encode_empty_table_as_object: wether to encode an empty table as an JSON object or array (default is object)

Returns

  • json: string — encoded json

Variables

json.null: unknown

Represents the null primitive from a json file