BeamMP-Server icon indicating copy to clipboard operation
BeamMP-Server copied to clipboard

[Bug] Util.JsonEncode considers tables with index 0 as arrays

Open my-name-is-samael opened this issue 1 year ago • 3 comments

Have you read our FAQ/Wiki/#before-you-ask ? Yes

Describe the bug When I use Util.JsonEncode on a LUA Object with index 0 (followed by 1, 2, 3, etc), the returned JSON string represents an array. LUA "arrays" (as I understand with ipairs) have indices starting with 1, so my example should be considered as an object when it is converted to JSON.

To Reproduce Steps to reproduce the behavior:

  1. Execute following code:
print(Util.JsonEncode({
    [0] = "a",
    [1] = true,
    [2] = 0.1
}))
  1. The result string is ["a",true,0.1] but should be {0:"a",1:true,2:0.1}

Expected behavior When passing to Util.JsonEncode a table containing an index out of the range 1-N (or present in subobjects), it should return an object and not an array

Desktop (please complete the following information):

  • OS Windows 11 Pro
  • BeamMP Server v3.4.1

my-name-is-samael avatar Jul 04 '24 11:07 my-name-is-samael

I'd like to add another weird behavior with tables to the ticket, with Util.JsonDecode this time:

When I run Util.JsonDecode('[1,null,3,4]') I expect to get this object : { [1] = 1, [3] = 3, [4] = 4 }

But instead I get : { [1] = 1, [2] = 3, [3] = 4 } or simplified { 1, 3, 4 }

The null 2nd index was completely omitted by the JSON parser

my-name-is-samael avatar Jun 24 '25 09:06 my-name-is-samael

I'd like to add another weird behavior with tables to the ticket, with Util.JsonDecode this time:

When I run Util.JsonDecode('[1,null,3,4]') I expect to get this object : { [1] = 1, [3] = 3, [4] = 4 }

But instead I get : { [1] = 1, [2] = 3, [3] = 4 } or simplified { 1, 3, 4 }

The null 2nd index was completely omitted by the JSON parser

i think you mean "nil" not "null" and i think an array entry that is nil is treated as non-existent in lua, so i dont think its an issue from the parser but rather basic lua behavior

boubouleuh avatar Jun 24 '25 11:06 boubouleuh

i think you mean "nil" not "null" and i think an array entry that is nil is treated as non-existent in lua, so i dont think its an issue from the parser but rather basic lua behavior

Not quite, you can nilifiy elements in a array table, but that wont update the indexies, which essentially just leads to holed tables

local myTable = {
  [1] = 1,
  [2] = 2,
  [3] = 3,
  [4] = 4
} -- this is equal to {1, 2, 3, 4}

myTable[2] = nil
print(myTable)

--[[
  [1] = 1
  [2] = nil
  [3] = 3
  [4] = 4
]]

Now i cant tell why where it causes this behaviour to correct the indexies in the encoding process, but maybe some information gets lost on the ffi layer from the lua state up to where the json is encoded. As far as i know thats done on the c++ side, not that i can know, not maintaining the server

OfficialLambdax avatar Jun 24 '25 11:06 OfficialLambdax