0

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"
      }
   ]
}
1
  • Which library do you use? Commented Jan 25, 2023 at 16:23

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You are right! I was using the lua-json that have this problem! Thank you Eskri.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.