Parsing json with cjson results in nil table

467 views
Skip to first unread message

Joel Parker

unread,
Sep 11, 2017, 9:18:26 AM9/11/17
to openresty-en
I am trying to parse some json and for some reason the table returned from decode is always nil. Maybe something wrong with the json string but it seems correct. Can anyone tell me what I am doing wrong ?

Here is the config for reference:

load_module modules/ndk_http_module.so;
load_module modules/ngx_http_lua_module.so;

# takes advantage of all the cores in a processor
worker_processes auto;

events {
    worker_connections  1024;
}

http {

    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;
    gzip  on;

    server {
        listen 80;
        server_name localhost;
        root /data/www;

        location / {
                content_by_lua '
                        local cjson = require("cjson")
                        json_text = [[ [{ "message": "somewhere over the rainbow", "key": "7F02D18E-88E7-486D-B51F-550118491CB1"}] ]]
                        value = cjson.decode(json_text)

                        say(cjson.encode(value)) -- returns nil ?
                        ngx.say( value["message"] )

                ';

                resolver 8.8.8.8;
        }

Rob Kay

unread,
Sep 11, 2017, 11:28:13 PM9/11/17
to openresty-en
There are a couple of issues with your code. The first is that you're calling say(cjson.encode(value)) instead of ngx.say(cjson.encode(value))

The second is that when you define json_text, you have put the json object inside a json array (the inner most square brackets). That means to reference "message" you actually have to reference the the position in the array (lua starts and 1 not 0) first. Try this:

local cjson = require("cjson")
local json_text = [[ [{ "message": "somewhere over the rainbow", "key": "7F02D18E-88E7-486D-B51F-550118491CB1"}] ]]
local value = cjson.decode(json_text)

ngx.say(cjson.encode(value)) 
ngx.say(value[1]["message"])

or alternatively:

local cjson = require("cjson")
local json_text = [[ { "message": "somewhere over the rainbow", "key": "7F02D18E-88E7-486D-B51F-550118491CB1"} ]]
local value = cjson.decode(json_text)

ngx.say(cjson.encode(value))
ngx.say(value["message"])
Reply all
Reply to author
Forward
0 new messages