Optionally allow stringification of numeric keys in tables when calling `lljson.encode()`
planned
WolfGang Senizen
I was trying to encode a table for debugging and it was just
{ [50] = true }
Maybe an object meta table would be useful?
lljson.object_mt
To mark a sparse array to be encoded as an object instead?
In the end i got around it using
slencode
but it might be useful to be able to output normal json with number keys, as a json object.Log In
H
Harold Linden
marked this post as
planned
H
Harold Linden
We have no way to losslessly-encode a sparse array as JSON without
slencode
because there's no way to encode object keys that aren't strings in standard JSON.WolfGang Senizen
Harold Linden That's why i was wondering if an object metatable would be usable, that way the scripter accepts, this is a json object, keys are strings, and so getting stuff cast to string would make sense.
H
Harold Linden
WolfGang Senizen Is there a situation where you'd actually _want_ that array index stringification behavior rather than it being an unintended side-effect? The only case I can think of is where you want sparse arrays to round-trip, and you need
slencode()
for thatWolfGang Senizen
Harold Linden I was trying to hit an api that uses keys as the id's for records
It is a bit contrived, and i could just convert to strings myself.
The needed request body looks something like this
{
"47": {
"name": "new name"
}
}
The idea was to update the record with id 47, in slua I was storing the data using numbers as keys, I could change it to strings, I just thought it might be worth offering the functionality.
I wouldn't deem this a priority of any kind though.
H
Harold Linden
WolfGang Senizen: Hmmm, yeah in that case I think that API would probably break if you passed a key with a low integer ID that actually got encoded as a sparse array.
I suppose stringification of integer keys for things we've specifically tagged as objects is actually acceptable with other JSON APIs when passing dicts / objects though:
sl@ip-192-168-5-11 server % python3
>>> import json
>>> json.dumps({15: "foo"})
'{"15": "foo"}'
sl@ip-192-168-5-11 server % node
> JSON.stringify({15: "foo"})
'{"15":"foo"}'
I think either an
lljson.object_mt
or just going with that behavior whenever it encountrs a table with an mt without __len
would work.