How to parse json in lua?

亡梦爱人 提交于 2019-12-12 12:50:21

问题


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.

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. Then I can let the nginx continue with its redirection. Can anybody please show me an example of how can I achieve that?


回答1:


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)

If have any qualms about the JSON data, you may want to run the string in L in a sandbox.



来源:https://stackoverflow.com/questions/42139363/how-to-parse-json-in-lua

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!