Skip to content

JsonDecode

JSON text as a value.

The reverse of JsonEncode, under the same rules: an object becomes a table with text keys, an array a table with the keys 1 to n, a JSON null inside them leaves the place empty (in an array the other values keep their positions: [1,null,3] has t[1] and t[3]), and an integer beyond 2^53 becomes a text of its digits. The text may be at most 1 MB and 32 levels deep.

A null on its own gives nil, so a nil result alone does not say the text was wrong - look at the second value. Text that is not valid JSON, or is too deep or too big, gives nil and the reason. Nothing in the text can run anything: what comes back is data.

JsonDecode(text)
Parameter Type
text string one JSON value

any, string | nil - the value - or nil and the reason when the text could not be read

-- a page's emitServer arrives as text: read it defensively
function OnClientEvent(pid, name, payload)
if name == "shop.buy" then
local order, why = JsonDecode(payload)
if type(order) ~= "table" or type(order.item) ~= "string" then
Log("bad order from " .. GetPlayerName(pid) .. ": " .. tostring(why))
return
end
buy(pid, order.item, tonumber(order.count) or 1)
end
end

JsonEncode · OnClientEvent · the Web interface group of the index