问题
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