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

How to use JSON Format for tables?

Asked by
Zeuxulaz 148
3 years ago

Ok, so I'm new to JSON Format.

Code:

local HttpService = game:GetService("HttpService")
local Table = {

    Children = game.Workspace:GetChildren(),
    Number = 2

}

print(Table) -- Just for experimentation purposes

local Code = HttpService:JSONEncode(Table)
print(Code)

I want to print Children (inside Table) as something like (maybe not exactly this, but like it): {"Camera", "Terrain"}

For this instance, there is only going to be Camera and Terrain inside game.Workspace, but I want it work for anything I add later automatically when you join. So if I added a Script to game.Workspace it would print: {"Camera, "Terrain", "Script"}.

Any ideas?

0
You can't have an instance reference within a JSON table. You can only have strings, numbers, or subtables. Fifkee 2017 — 3y

1 answer

Log in to vote
0
Answered by
Sparks 534 Moderation Voter
3 years ago

You cannot encode objects into JSON. From what I could tell from your print example, you are able to encode the NAMES of these objects as they are string values. To do so, and for all future objects added to workspace, you may do this:

local HttpService = game:GetService("HttpService")

local children = game.Workspace:GetChildren()
local Table = {
        Number = 2,
        Children = {}
}

for i,v in pairs(children) do
    table.insert(Table["Children"], v.Name)
end

local Code = HttpService:JSONEncode(Table)
print(Code)

workspace.ChildAdded:Connect(function(child)
    if child ~= nil then --Just to be safe since nil doesn't have a Name property
        table.insert(Table["Children"], child.Name)
        Code = HttpService:JSONEncode(Table)
    end
end)


-- TEST
wait(3)
local t = Instance.new("Motor6D", workspace)
print(Code)
0
Thanks! This makes a lot of sense now; thanks for teaching me more about JSON Format! Zeuxulaz 148 — 3y
Ad

Answer this question