简体   繁体   English

如何在lua中解析json?

[英]How to parse json in lua?

Is there any lightweight, preferably pure lua, library for lua to parse json content? 是否有任何轻量级,最好是纯lua,用于lua解析json内容的库? 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 . 基本上我想用一个lua模块扩充我的ngnix,需要从我从Redis获得的json对象中验证一些信息。

The object looks like as follow: 该对象如下所示:

{
  "data": {
    "user": {
      "username": "username",
      "type": "TYPE"
    }
  },
  "passport": {
    "user": "uuid"
  },
}

In my lua code, I need to verify if the data.user.username exists. 在我的lua代码中,我需要验证data.user.username存在。 Then I can let the nginx continue with its redirection. 然后我可以让nginx继续重定向。 Can anybody please show me an example of how can I achieve that? 有谁能告诉我一个如何实现这一目标的例子?

JSON data in that form is very close to Lua tables. 该表单中的JSON数据非常接近Lua表。 So you can transform the JSON data into Lua code and run it, if you trust the JSON data. 因此,如果您信任JSON数据,则可以将JSON数据转换为Lua代码并运行它。

J=[[
{
  "data": {
    "user": {
      "username": "username",
      "type": "TYPE"
    }
  },
  "passport": {
    "user": "uuid"
  },
}
]]
L="return "..J:gsub('("[^"]-"):','[%1]=')
T=loadstring(L)()
print(T.data.user.username)

If have any qualms about the JSON data, you may want to run the string in L in a sandbox. 如果对JSON数据有任何疑虑,您可能希望在沙箱中运行L中的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM