Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Example usage of JSONEncode?

Asked by
EmK530 143
3 years ago
Edited 3 years ago

I've never really had a use for JSONEncode (function in HttpService) but I felt like figuring out how it was used incase I might need to know it in the future so I wanted to test if someone on ScriptingHelpers knew the answer.

Thanks!

1 answer

Log in to vote
1
Answered by 3 years ago
Edited 2 years ago

Hiya, JSONEncode is useful for transforming a Lua table to a JSON object or array.

Although there are limits to this function.

  • 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 ***.

A good use for this function is when you're sending JSON data to a Discord Webhook to send a message in a specific channel.

An example of this is:

local HttpService = game:GetService("HttpService")
local WebhookURL = "https://discordapp.com/api/webhooks/xxxxxx/xxxxxxx"

local MessageData = {
    ["content"] = "Hoi, Test Message arrived!"
}

MessageData = HttpService:JSONEncode(MessageData)
-- We used JSONEncode to convert the Lua Table into a Json String 

HttpService:PostAsync(WebhookURL, MessageData)

this is an example I found on the Roblox DevForum (https://devforum.roblox.com/t/discord-webhooks-integrating-roblox-with-discord/458366)

I hope this helps you with your scripts in the future! If you don't understand anything I just said, feel free to comment on this post telling me! :)

Ad

Answer this question