Home > Software engineering >  Problem to enconde table to json (string index expected, got number)
Problem to enconde table to json (string index expected, got number)

Time:01-26

I have the following table:

local my_table = {data = {{value1 = "test1", value2 = "test2"}, {value3 = "test3", value4 = "test4"}}}

I want to convert this table to json format and save to a file. But, when I tried

json.encode(my_table)

I got an error: bad argument #1 to 'encode' (["data"] => string index expected, got number)

I expect the json:

{
   "data":[
      {
         "value1":"test1",
         "value2":"test2"
      },
      {
         "value3":"test3",
         "value4":"test4"
      }
   ]
}

CodePudding user response:

It works!

local json = require'json'
local my_table = {data = {{value1 = "test1", value2 = "test2"}, {value3 = "test3", value4 = "test4"}}}
print(json.encode(my_table))  -- {"data":[{"value1":"test1","value2":"test2"},{"value4":"test4","value3":"test3"}]}

I'm using this repo

Probably, the implementation you are using requires special syntax to treat Lua table as JSON array instead of JSON dictionary.
The implementation I'm using makes this decision (is it an array or a dictionary) automatically.

  • Related