JSONEncode
The JSONEncode function transforms a Lua table into a JSON object or array based on the following guidelines:
- Keys of the table must be either strings or numbers. If a table contains both, an array takes priority (string keys are ignored).
- An empty Lua table
{}
generates an empty JSON array. - The value
nil
is never generated. - Cyclic table references generate the string
*** certain entries belong to the same table ***
.
This function allows values such as inf and nan, which are not valid JSON. This may cause problems if you want to use the outputted JSON elsewhere.
To reverse the encoding process, and decode a JSON object, you can use HttpService|HttpService's
HttpService/JSONDecode
function.
Many web endpoints use JSON, as it is commonly used on the Internet. Visit JSON.org to become more familiar with the format.
This method can be used regardless of whether HTTP Requests are HttpService/HttpEnabled|enabled
.
Parameters
Name | Type | Default | Description |
---|---|---|---|
|
The input Lua table |
Returns
Return Type | Summary |
---|---|
The returned JSON string |
Code Samples
HttpService JSONEncode
This code sample turns a Lua table tab
into a JSON string using HttpService’s JSONEncode. Then, it prints out the string. Note that after the table is set, the sample creates a cyclic reference in the table by putting a reference to the table within itself. This is to demonstrate how the JSON encoder handles cyclic references.
Try editing the Lua table to see how the JSON output changes.
local HttpService = game:GetService("HttpService") local tab = { -- Remember: these lines are equivalent ["message"] = "succes"; message = "success"; info = { points = 120, isLeader = true, user = { id = 12345, name = "JohnDoe" }, past_scores = {50, 42, 95}, best_friend = nil } } -- A cyclic relationship like this... tab.tab = tab -- ...will be replaced with the string: -- '* certain entries belong to the same table '* local json = HttpService:JSONEncode(tab) print(json)