0
votes

Following script describes the decoding of a JSON Object, that is received via MQTT. In this case, we shall take following JSON Object as an example:

{"00-06-77-2f-37-94":{"publish_topic":"/stations/test","sample_rate":5000}} 

After being received and decoded in the handleOnReceive function, the local function saveTable is called up with the decoded object which looks like:

["00-06-77-2f-37-94"] = {
    publish_topic = "/stations/test",
    sample_rate = 5000
  }

The goal of the saveTable function is to go through the table above and assign the values "/stations/test" and 5000 respectively to the variables pubtop and rate. When I however print each of both variables, nil is returned in both cases. How can I extract the values of this table and save them in mentioned variables?

If i can only save the values "publish_topic = "/stations/test"" and "sample_rate = 5000" at first, would I need to parse these to get the values above and save them, or is there another way?

local pubtop
local rate

local function saveTable(t)
  local conversionTable = {}
  
  for k,v in pairs(t) do
    if type(v) == "table" then
      conversionTable [k] = string.format("%q: {", k)
      printTable(v)
      print("}")
    else
      print(string.format("%q:", k) .. v .. ",")
    end
  end

  pubtop = conversionTable[0]
  rate = conversionTable[1]  
end

local lua_value

local function handleOnReceive(topic, data, _, _)
  print("handleOnReceive: topic '" .. topic .. "' message '" .. data .. "'")
  print(data)
  lua_value = JSON:decode(data)

  saveTable(lua_value)

  print(pubtop)
  print(rate)
end
client:register('OnReceive', handleOnReceive)

previous question to thread: Decode and Parse JSON to Lua

1

1 Answers

0
votes

The function I gave you was to recursively print table contents. It was not ment to be modified to get some specific values. Your modifications do not make any sense. Why would you store that string in conversionTable[k]? You obviously have no idea what you're doing here. No offense but you should learn some basics befor you continue.

I gave you that function so you can print whatever is the result of your json decode.

If you know you get what you expect there is no point in recursively iterating through that table.

Just do it like that

for k,v in pairs(lua_value) do
  print(k)
  print(v.publish_topic)
  print(v.sample_rate)
end

Now read the Lua reference manual and do some beginners tutorials please. You're wasting a lot of time and resources if you're trying to implement things like that if you do not know how to access the elements of a table. This is like the most basic and important operation in Lua.