John
John

Reputation: 43

Insert all the attributes and values of JSON in to LUA table

I would like to insert the attribute names and values of a JSON in to LUA table.

local function convert_table(tbl_test)
 local output_table = {}
  for i, v in pairs(tbl_test) do
    output_table [string.lower(i)] = string.lower(v)                     
  end  
 return output_table
end
  local  test  =  cjson.decode(inputJson)
  local  final =  convert_table(test)

This is working if my JSON is

 {    "test": "abc",
      "test1": "EDF",
      "test2": "PNG" }

But it is not working for below JSON (JSON inside a JSON)

{
  "upper": {
    "test": "abc",
    "test1": "EDF",
    "test2": "PNG",
  }, 
  "lower": {
    "test3": "aabc",
    "test4": "edfa",
    "test5": "png"
  }
}

Upvotes: 1

Views: 359

Answers (1)

DarkWiiPlayer
DarkWiiPlayer

Reputation: 7064

While it is possible to parse nested constructs like the above JSON example using Luas pattern maching, that's far from its intended purpose and generally just way to complicated for anything other than a dedicated library for that purpose.

A more viable solution: Either use a more powerful tool like LPEG¹ to build your parser (Which will still take some time), or just use any of the available json parsers for Lua² ³.

Upvotes: 1

Related Questions