Access JSON Chained

0

I am working in the lua language of CORONASDK and I run into a JSON of this type:

[  
   {      
     "data":{  
         "online":true,
         "peerId":1,
         "id":"5af10ec611686d7373de1b98",
         "scriptData":{  
            "PROFILE":{  
               "religion":"Cristiaismo",
               "OS":"Heterosexual",
               "pais":"Colombia",
               "sexo":"Femenino",
               "PP":"Polo Democrático",
               "email":"",
               "maxScore":0,
               "user":"motorolaef31",
               "raza":"Afrodescendiente",
               "lang":"Inglés",
               "edad":"< 18"
            }
         },
         "externalIds":{  

         },
         "displayName":"motorolaef31"
      }
   }
]

I need to access the "PROFILE" attribute how could I do that?

    
asked by Wzap PepexD 08.05.2018 в 13:18
source

1 answer

0

You have to call the json library as follows:

pcall(function() require "json" end)

The pcall is to capture the error as false I do not know if in the case of CORONA SDK this library comes by default.

Then we proceed to read the dataJson.json file (so I called the file you showed above) in the path that you have saved as follows:

local file = io.open("/miPC/miRuta/dataJson.json", "r")
local data = file:read("*a")

Finally we use the function decode of the library json with the previously read file

tb = json.decode(data)

Now comes the part of understanding how to read the table that has been generated in Lua

for k, v in pairs(tb) do print(k,v) end
-- se imprime: 1, table: 0x35ce7838

It implies that there is a table inside the brackets [] in tb

Perform the following queries sequentially and you will see how you can obtain the attributes in the original json file

for k, v in pairs(tb[1]) do print(k,v) end
-- se imprime: data,    table: 0x35ce7698

for k, v in pairs(tb[1]["data"]) do print(k,v) end
--[[
    ------------
    Se imprime:
    ------------
    scriptData  table: 0x35ce7760
    peerId  1
    id  5af10ec611686d7373de1b98
    online  true
    externalIds table: 0x35ce7cc0
    displayName motorolaef31
]]

for k, v in pairs(tb[1]["data"]["scriptData"]) do print(k,v) end
-- se imprime: PROFILE  table: 0x35ce78a0

for k, v in pairs(tb[1]["data"]["scriptData"]["PROFILE"]) do print(k,v) end
--[[
    ------------
    Se imprime:
    ------------
    religion    Cristiaismo
    OS  Heterosexual
    pais    Colombia
    maxScore    0
    PP  Polo Democrático
    email   
    sexo    Femenino
    user    motorolaef31
    raza    Afrodescendiente
    lang    Inglés
    edad    < 18
]]
    
answered by 29.05.2018 / 05:36
source