如何使用Lua模式解析JSON数据?

时间:2019-09-17 10:15:29

标签: json nginx lua gsub lua-patterns

我正在将lua-module集成到nginx中。我想检查参数的值是否为空。每当我使用以下代码时,针对JSON请求都会得到真实的结果

请求

{
  "data": {
    "user": {
      "username": "Ethen",
      "type": "PDF"
    }
  },
  "passport": {
    "user": "001"
  },
}

代码

local arg = ngx.req.get_body_data();
L="return "..arg:gsub('("[^"]-"):','[%1]=')
T=loadstring(L)()
ngx.print(T.data.user.username)
if T.data.user.username == "" then
    ngx.say("Empty username");
end  

但是当我使用此请求时,出现了错误(试图调用nil值堆栈回溯) 请求

    {
    "reference"    : "567456314",
    "callback_url" : "http://www.example.com/",
    "verification_mode" : "any",

    "document"         : {
        "proof"           : "data:image/png;base64,iVBOR=“,
        "additional_proof": "data:image/png;base64,iVBORw0=",
        "supported_types" : ["id_card","driving_license","passport"], 
        "expiry_date"     : "",
        "document_number" : ""
    },

    "address"         : {
        "proof"            : "data:image/png;base64,iVBORw0KG=",
        "supported_types"  : ["id_card","bank_statement"],
        "name"             : "",
        "issue_date":""
    }
}

代码

local arg = ngx.req.get_body_data();
L="return "..arg:gsub('("[^"]-"):','[%1]=')
T=loadstring(L)()
ngx.print(T.document.proof)
if T.document.proof == "" then
    ngx.say("Empty proof");
end  

有什么问题和解决方案吗?? ...谢谢!!

0 个答案:

没有答案