Skip to content

Add fromJSON argument to always convert keys to numbers if possible #4515

@PlatinMTA

Description

@PlatinMTA

Is your feature request related to a problem? Please describe.

Let's say you have a table that saves a numeric key with a value, something like:

{
    [1] = true,
    [2] = true,
    [3] = true,
}

If you convert it to JSON, the table will automatically be converted into:

[[true, true, true]]

When you retrieve this JSON string and you convert it back to lua, the table is basically the same. This is convenient.

But let's say your table looks more like this:

{
    [1] = true,
    [3] = true,
}

Now, JSON will save it like this:

[ { "1": true, "3": true } ]

So when you convert it back to a lua table, it will look more like this:

{
    ["1"] = true,
    ["3"] = true,
}

Since this is not javascript, trying to retrieve the value on the key 1 will return nil, because it is technically "1", a string. This can be circumvented with:

local table = fromJSON(jsonString)
local fixedTable = {}
for key,value in pairs(table) do
    fixedTable[tonumber(key)] = value
end
table = fixedTable

This is OK, but I think it would be more practical if you could just return the table from fromJSON already with the numeric keys transformed from strings to numbers.

Describe the solution you'd like

Add an argument in the fromJSON function that tells the engine to automatically convert any string into number, if the string can be converted into a number.

fromJSON( string json, boolean convertStringsToNumbers )

By default this argument should be false.

Describe alternatives you've considered

No response

Additional context

Pretty niche, but I have encountered this issue more times that I would like to admit. Everything works until you have to save the table into a JSON string, and then you have to make a custom fromJSON function for everything to work as intented.

Nothing really game breaking to be solved here, just a nice QoL addition.

And yes this should be recursive.

Security Policy

  • I have read and understood the Security Policy and this issue is not about a cheat or security vulnerability.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions