3

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?

2
  • The easy answer just pick library you like. There many of them :) Commented Feb 9, 2017 at 14:44
  • 1
    1, 2 Commented Feb 9, 2017 at 16:53

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Why would you use loadstring?
@warspyking Because among the "pure lua" ways, this is almost certainly the fastest. And it can be done in a safe way. (Unless there's a really ugly bug in the Lua parser, but that's quite unlikely.) Further, there's a difference in threat level between e.g. a web API exposed to unknown (and quite likely some malicious) data and a tool that you use to quickly load data generated out of some other trusted tool running locally (even if that tool interfaces with the 'net).
I understand what it does, but loadstring for something so simple is really expensive don't you think?
@warspyking, I doubt that hand-written JOSN parsers in pure Lua will be faster or use less memory than the Lua parser, but I haven't measured anything.
This is works only for limited subset of JSON. And even in this example JSON is not valid but it parse without any error.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.