json.decode

March 26, 2020 Contributors

Name

json.decode — Create a JSON object from a JSON string

Synopsis

require(‘json’);

json.decode(str);

str: string

Description

Create a JSON object from a JSON string. On success this function returns a JSON object. On failure the JSON object is nil and an error code and an error message are returned. Use json.strerror to return a description of JSON error codes. You can also use json.new to create an empty JSON object.

obj, code, err = json.decode([[{ "hello": "world" }]]);
if not obj then
 error(err);
end
print(obj.hello); -- { "hello": "world" }
obj.int = 4;
obj.num = 3.5;
print(obj); -- { "hello": "world", "int": 4, "num": 3.500000 }

Enable this function with the statement require("json");.

You can directly assign a primitive to the field of a JSON object. Lua tables, whether they are objects or arrays, are a different matter; See json.encode for more information.

See Also

json.encode