JSONEncode() Breaks with trailing nil values in arrays

As you can see, when I put a nil value at the end of the array, it removes the other nil value and the 5. The error occurs when the last value in an array is nil.

print(game:GetService(“HttpService”):JSONEncode({1, nil, 3}))
[1,null,3]
print(game:GetService(“HttpService”):JSONEncode({1, 4,{1, nil, 3}, nil, 5}))
[1,4,[1,null,3],null,5]
print(game:GetService(“HttpService”):JSONEncode({1, 4,{1, nil, 3}, nil, 5, nil}))
[1,4,[1,null,3]]
print(game:GetService(“HttpService”):JSONEncode({1, 4,{1, nil, 3, nil}, nil, 5, nil}))
[1,4,[1]]
print(game:GetService(“HttpService”):JSONEncode({1, 4,{1, nil, 3, nil}, nil, 5, nil, nil}))
[1,4,[1],null,5]
print(game:GetService(“HttpService”):JSONEncode({1, 4,{1, nil, 3, nil}, nil, 5, nil, nil, nil}))
[1,4,[1]]
print(game:GetService(“HttpService”):JSONEncode({1, 4,{1, nil, 3, nil}, nil, 5, nil, nil, nil, nil}))
[1,4,[1]]

The behavior seems to vary with different numbers of trailing nil values.

1 Like

I tried to run print(#{1, 4,{1, nil, 3, nil}, nil, 5, nil}), and it gave me the number 3. Running print(#{1, 4,{1, nil, 3}, nil, 5}) gave me 5. My guess is the JSON parser is doing something like this:

for i = 1, #Table do
EncodeItem(Table[i])
end

I prefer to use my own saving system because I have been having too many problems with JSONEncode.

1 Like

This does appear to be an issue with the Lua length operator…

I guess I will be using some goofy work around.
http://lua-users.org/wiki/StoringNilsInTables

Lua’s select function usually solves this issue.

print(select("#", unpack(Table))
for i = 1, select("#", unpack(Table)) do
    EncodeItem(Table[i])
end

Edit: Although it might still have issues with trailing nils now that I think about it.