PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience
Collapse Sidebar

JSONDecode

The JSONDecode function transforms a JSON object or array into a Lua table with the following characteristics:

  • Keys of the table are strings or numbers but not both. If a JSON object contains both, string keys are ignored.
  • An empty JSON object generates an empty Lua table {}.
  • If the input string is not a valid JSON object, this function will throw an error.

To encode a Lua table into a JSON object, you can use HttpService|HttpService's HttpService/JSONEncode 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 JSON object being decoded

Returns

Return Type Summary

The decoded JSON object as a Lua table


Code Samples


HttpService JSONDecode

This code sample gives an example JSON format string and parses it using HttpService’s JSONDecode. It then verifies that the JSON was parsed correctly, and prints out some of the information within the object.

Try editing the JSON string to experiment with the format. Also experiment with inspecting the data in Lua to get comfortable with the Lua representation of the data (tables and other values).

local HttpService = game:GetService("HttpService")

-- An example JSON formatted string 
-- For details, see: http://www.json.org/
local jsonString = [[
{
	"message": "success",
	"info": {
		"points": 120,
		"isLeader": true,
		"user": {
			"id": 12345,
			"name": "JohnDoe"
		},
		"past_scores": [50, 42, 95],
		"best_friend": null
	}
}
]]

local data = HttpService:JSONDecode(jsonString)
if data.message == "success" then
	-- Print the sample data
		
	-- Since tab["hello"] and tab.hello are equivalent,
	-- you could also use data["info"]["points"] here:
	print("I have " .. data.info.points .. " points")
	if data.info.isLeader then
		print("I am the leader")
	end
	print("I have " .. #data.info.past_scores .. " past scores")
	
	print("All the information:")
	for k, v in pairs(data.info) do
		print(k, type(v), v)
	end
end