Convert string into table

I want to convert a string that looks like this:

"{a = 1,b = 2,b = 3}" --I want to convert this string into {a = 1,b = 2,b = 3}

into the table version (above is just an example)
But how would I be able to do that with scripts? i have no idea

Here is a solution from stackoverflow for a similar question using gmatch. Ideally, you’d create a recursive function or a string capture that would translate the string into a dictionary, but I’m not a string guru.

loadstring is also an option but that’s a bad idea for… many reasons.

We have a function for this:

local data = game.HttpService:JSONDecode(yourString)
print(data)

Although keep in mind that one of your b indexes will be discarded/removed, that’s because dictionaries must have unique keys.

1 Like

@Negativize had the correct method, though you have to add “return” to the string and call it. Here are some steps to help you out.

  1. Enabled the ‘LoadStringEnabled’ property under ServerScriptService
    image
  2. Code!
local str = "{a = 1, b = 2, c = 3}"
local code = "return " .. str
local func = loadstring(code)
local dictionary = func()

for key, value in pairs(dictionary) do
	print(key, value)
end

However, I wouldn’t use loadstring() as it can lead to some exploits and other issues. I would try to find another way of what you’re trying to achieve, as I’m sure there is a better way of doing this. @NyrionDev’s method would also work but I’d still try to find a way that you can do without any of these methods.

yeah im going with nyrion’s idea, because the tables i want to convert have tables inside tables inside tables inside tables etc. only problem is json cant encode values like color cframe etc but im working on a fix

You’ll have to serialize the ROBLOX data into a form JSON can digest, i.e. turning a Color3 value into a table with Color3={r=100,g=100,b=100} and turning that back into a Color3 object when you read the JSON data

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.