如何在lua中解析json? [英] How to parse json in lua?
问题描述
是否有用于lua解析json内容的轻量级(最好是纯lua)库?基本上,我想通过lua模块扩展我的ngnix,该模块需要验证我从Redis
获取的json
对象的一些信息.
Is there any lightweight, preferably pure lua, library for lua to parse json content? Basically I wanna augment my ngnix with a lua module that needs to verfiy some information from a json
object I'm getting from Redis
.
该对象如下所示:
{
"data": {
"user": {
"username": "username",
"type": "TYPE"
}
},
"passport": {
"user": "uuid"
},
}
在我的lua代码中,我需要验证data.user.username
是否存在.然后,我可以让Nginx继续其重定向.有人可以告诉我如何实现该目标的例子吗?
In my lua code, I need to verify if the data.user.username
exists. Then I can let the nginx continue with its redirection. Can anybody please show me an example of how can I achieve that?
推荐答案
这种形式的JSON数据非常接近Lua表.因此,如果您信任JSON数据,则可以将JSON数据转换为Lua代码并运行它.
JSON data in that form is very close to Lua tables. So you can transform the JSON data into Lua code and run it, if you trust the JSON data.
J=[[
{
"data": {
"user": {
"username": "username",
"type": "TYPE"
}
},
"passport": {
"user": "uuid"
},
}
]]
L="return "..J:gsub('("[^"]-"):','[%1]=')
T=loadstring(L)()
print(T.data.user.username)
如果对JSON数据有任何疑问,您可能希望在沙箱中的L
中运行字符串.
If have any qualms about the JSON data, you may want to run the string in L
in a sandbox.
这篇关于如何在lua中解析json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!