解码和解析JSON到Lua
2021-2-14 10:20:26
收藏:0
阅读:121
评论:1
我有以下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
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
- 如何编写 Lua 模式将字符串(嵌套数组)转换为真正的数组?
我不知道您使用的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)
`` `