【发布时间】:2021-05-16 23:14:27
【问题描述】:
我有以下 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
Edit2:@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)
【问题讨论】: