使用 Openresty 中的 cjson Lua 模块解析缺少字段的 JSON

问题描述

我正在尝试解析通过 POST 请求发送到 Nginx/Openresty location 的 json 有效负载。为此,我像这样将 Openresty 的 content_by_lua_block 与其 cjson module 结合起来:

# other locations above

location /test {                                                                                                               
    content_by_lua_block {                                                                                                 
        ngx.req.read_body()                                                                                            
        local data_string = ngx.req.get_body_data()                                                                    
                                                                                                                        
        local cjson = require "cjson.safe"                                                                             
        local json = cjson.decode(data_string)                                                                         
                                                                                                                        
        local endpoint_name = json['endpoint']['name']                                                             
        local payload = json['payload']                                                                            
        local source_address = json['source_address']                                                              
        local submit_date = json['submit_date']                                                                    
                                                                                                                            
        ngx.say('Parsed')                                                                                     
                                                                                                                            
    }                                                                                                                      
}                                                                                                               

解析包含所有必填字段的示例数据按预期工作。正确的 JSON 对象可能如下所示:

{
    "payload": "the payload here","submit_date": "2018-08-17 16:31:51",},"endpoint": {
        "name": "name of the endpoint here"
    },"source_address": "source address here",}

但是,用户可能会向 location 发布不同格式的 JSON 对象。假设一个简单的 JSON 文档,如

{
    "username": "JohnDoe","password": "password123"
}

不包含所需的字段/键。

根据cjson module docs,如果遇到无效数据,使用cjson(没有其safe 模式)将引发错误。为了防止出现任何错误,我决定通过导入 safe 来使用其 cjson.safe 模式。对于无效数据,这应该返回 nil 并提供错误消息而不是引发错误

如果遇到任何无效数据,cjson 模块将在 JSON 转换期间抛出错误。 [...]

cjson.safe 模块的行为与 cjson 模块相同,除非在 JSON 转换期间遇到错误。出错时,cjson_safe.encodecjson_safe.decode 函数将返回 nil,后跟错误消息。

但是,在我的案例中,我没有遇到任何不同的错误处理行为,Openresty 的 error.log 文件显示了以下回溯:

2021/04/30 20:33:16 [错误] 6176#6176:*176 lua 入口线程中止:运行时错误:content_by_lua(samplesite:50):16:尝试索引字段“端点”(零值) )

这又会导致内部服务器错误

<html>                                                                                                                                 
<head><title>500 Internal Server Error</title></head>                                                                                  
<body>                                                                                                                                 
<center><h1>500 Internal Server Error</h1></center>                                                                                    
<hr><center>openresty</center>                                                                                                         
</body>                                                                                                                                
</html> 

我认为一种解决方法可能是编写一个专用函数来解析 JSON 数据并使用 pcall() 调用它以捕获任何错误。但是,这会使 safe 模式变得毫无用处。我在这里错过了什么?

解决方法

您的“简单 JSON 文档”是一个 有效 JSON 文档。您遇到的错误与 cjson 无关,这是一个标准的 Lua 错误:

resty -e 'local t = {foo = 1}; print(t["foo"]); print(t["foo"]["bar"])'
1
ERROR: (command line -e):1: attempt to index field 'foo' (a number value)
stack traceback:
    ...

cjson.safe 的“安全性”是关于解析格式错误的文档:

  • cjson 模块引发错误:

      resty -e 'print(require("cjson").decode("[1,2,3"))' 
      ERROR: (command line -e):1: Expected comma or array end but found T_END at character 9
      stack traceback:
          ...
    
  • cjson.safe 返回 nil 和错误消息:

    resty -e 'print(require("cjson.safe").decode("[1,3"))'
    nilExpected comma or array end but found T_END at character 9