解码和解析JSON到Lua

我有以下JSON数据,我想将其解码到Lua中,以访问每个publish_topic和sample_rate的值。

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

如果我理解正确,Lua表将是这样的:

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

接下来,我将遍历表,将每个值保存到本地变量中。

但是,如果我尝试打印表的值(使用下面的代码),我会得到返回值 'nil'。读取表格值的代码有问题吗?表格是有两个值还是只有一个:["publish_topic":"/stations/test","sample_rate":5000]?

lua_value = JSON:decode(data)

  for _,d in pairs(lua_value) do
    print(lua_value[d])
  end

local topic = lua_value[0]
local timer = lua_value[1]

end

编辑:我正在使用Lua的以下JSON库:http://regex.info/blog/lua/json

编辑2: @Piglet: 我实现了您的脚本,并添加了一个表(conversionTable),其中"publish_topic":"/stations/test"和"sample_rate:5000"这两个元素将分别保存在变量pubtop和rate中。但是,当我打印这两个变量中的每个变量时,都会返回nil。 如何从此表中提取信息以保存在变量中?

最终,我实际上只想将值"/stations/test"和"5000"保存到这些变量中。我需要提取上面的每个元素才能得到这些,还是有另一种方法?

local pubtop
local rate
local function printTable(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 .. "'")
  -- This sample publishes the received messages to test/topic2
  print(data)
  lua_value = JSON:decode(data)

  printTable(lua_value)

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

原文链接 https://stackoverflow.com/questions/66184796

点赞
stackoverflow用户2858170
stackoverflow用户2858170

我不知道您使用的json库是哪一个,因此我无法告诉您JSON:decode(data)是否是正确的方法。

假设lua_value如下所示:

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

然后你的循环

` for _,d in pairs(lua_value)do     print(lua_value [d])   end `

确实会打印出nil

lua_value在键“00-06-77-2f-37-94”上有一个单独的元素,该元素是一个表。

每次循环迭代都会给您一个键值对。因此,d实际上是值,因此是lua_value的内部表。

所以你实际上正在做:

`` ` local innerTable = lua_value [“00-06-77-2f-37-94”] print(lua_value [innerTable])

```

当然lua_value [innerTable]nil

##编辑:

尝试类似的内容

`` ` function printTable(t)   for k,v in pairs(t)do     if type(v)==“table”then       print(string.format(“%q:{”,k))       printTable(v)       print(“}”)     else       print(string.format(“%q:”,k)..v ..“,”)     end   end end

printTable(lua_value)

`` `

2021-02-13 12:57:02