Problem to encode/decode an array

Hello,

I noticed it’s not possible to encode then decode an array if attributs and values are mixed, for example :

local json = require( “json” )

local data={}
data[1]={}
data[1][1]=10 --value
data[1].a=20 --attribut

local encoded=json.encode(data)
print(encoded) – => [{“1”:10,“a”:20}]

But when decoded by:

data=json.decode(encoded)

It doesn’t work properly :

print(data[1]) – =>table xxxxx
print(data[1][1]) – => nil !!! Why ??? The value 10 is lost!
print(data[1].a) – 20

In fact, if I directly write the array under the following form all its data are preserved:

data={{a=20,10}}

So, is there a way to convert this kind of mixed arrays to a string so that I can save/load them?

hi waltsir,

you can see from the json output that the key for 1 has changed from an integer to a string.

try this:

print( data[1]["1"] )

Lua tables are a bit confusing because they have the dual nature of array/dictionary depending on how you use them. though the overarching data storage concept is the same, there are some subtle differences when you get down to the nuts and bolts of this duality. such as, apparently dictionary keys can only be strings. :slight_smile:

so this would be similar and correct to what you had before:

data[1]["1"]=10 data[1]["a"]=20

the safest thing is to treat a table as one or the other, but if you really want to do this i would suggest simply converting the integer to a string, then you’ll both be happy. :slight_smile:

local idx = tostring( 1 ) -- your variable here data[1][idx]=10 data[1].a=20

cheers,
dmc

Thanks very much, you found the secret of lua tables!

hi waltsir,

you can see from the json output that the key for 1 has changed from an integer to a string.

try this:

print( data[1]["1"] )

Lua tables are a bit confusing because they have the dual nature of array/dictionary depending on how you use them. though the overarching data storage concept is the same, there are some subtle differences when you get down to the nuts and bolts of this duality. such as, apparently dictionary keys can only be strings. :slight_smile:

so this would be similar and correct to what you had before:

data[1]["1"]=10 data[1]["a"]=20

the safest thing is to treat a table as one or the other, but if you really want to do this i would suggest simply converting the integer to a string, then you’ll both be happy. :slight_smile:

local idx = tostring( 1 ) -- your variable here data[1][idx]=10 data[1].a=20

cheers,
dmc

Thanks very much, you found the secret of lua tables!