2

I want to decode a multi layered json object into a table and print the value of "temp".

p=666
d=23.42
payload='{"d":
             {"pres":'..(p)..',"temp":'..(d)..'}
         }'

t = cjson.decode(payload)

My first idea was something like this:

print(t["d"]["temp"])

But this did not work. How can I improve this code so that it correctly decodes using Lua-CJson?

Marcel Stör
  • 22,695
  • 19
  • 92
  • 198
trahloff
  • 607
  • 1
  • 9
  • 17

2 Answers2

3

You cannot have line breaks in quoted strings.

There are two solutions:

  • remove the line breaks from '...'.

    payload='{"d": {"pres":'..(p)..',"temp":'..(d)..'} }'

  • use the long string form: [[ ... ], which allows line breaks.

    payload=[[{"d": {"pres":]]..(p)..',"temp":'..(d)..[[} }]]

You may also use a template, which makes things clearer:

p=666
d=23.42
payload=[[
    { "d":
            {"pres": (p), "temp": (d)}
    }'
]]  
payload=payload:gsub("%((.-)%)",_G)
print(payload)

If your fields are not global variables, put them in a table and use that table instead of _G.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • Thanks for the hint with the linebreak. But my main problem was that I have a multi layered json object that is parsed into a lua table with cjson.decode. This lua table acts like an array but I can only access key:value pairs from the first layer with something like this: print(t["d"]) but I want to access the value "temp" in the second layer but found no way to do this. – trahloff Feb 01 '16 at 20:17
0

Nesting Json directly does not seem to work with cJson ( atleast not on the ESP8266 with NodeMCU ) I found a solution by wrapping an array around the nested values.

p = 666
d = "23.42"
payload='{"d":[{"pres":'..(p)..',"temp":"'..(d)..'"}]}'
t = cjson.decode(payload)
print(t.d[1].temp) -- prints "23.42"

# Note 1 - this means you have to address the array before calling the variable t.d[1] - Arrays in Lua begin with the number 1 and are NOT zero-based like many other scripting languages.

# Note 2 - for some reason I got a 'Malformed number' error with the floating point value ( variable d ). As a string the value is decoded without error. I had to make the variable a string and put "double quotation marks" around the value. --> ah I found out I was working on a integer version of nodeMCU - which apparently does not support floating point numbers ...

DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
J.T. Houtenbos
  • 956
  • 7
  • 17