0

I am trying to run the cjson decode example found in the manual :

and I can't seem to get it to work.

Here is the relevant config:

 location / {
            content_by_lua '
                    local cjson = require("cjson")
                    json_text = '[ true, { "foo": "bar" } ]'
                    value = cjson.decode(json_text)
                    ngx.say(value)
            ';

            resolver 8.8.8.8;
    }

I get this error :

sudo nginx -t
nginx: [emerg] unexpected "[" in /etc/nginx/nginx.conf:29
nginx: configuration file /etc/nginx/nginx.conf test failed

if I remove the square brackets I get:

sudo nginx -t
nginx: [emerg] directive "content_by_lua" is not terminated by ";" in  /etc/nginx/nginx.conf:28
nginx: configuration file /etc/nginx/nginx.conf test failed

Does anyone have any idea what I am doing wrong ? It seems like cjson should be a fairly easy way to parse json in NGINX and I know people are doing it ... just can't figure out why even the example code isn't working for me.

Joel Parker
  • 295
  • 1
  • 4
  • 17
  • 2
    Your problem is the quote delimiter in `json_text = '[ true, { "foo": "bar" } ]'`, that is also a delimiter for `content_by_lua`. Instead, you can write: `json_text = [[ [ true, { "foo": "bar" } ] ]]`. Look at [the Lua manual](https://www.lua.org/manual/5.3/manual.html#3.1) for the long format for strings. – Alban Linard Sep 10 '17 at 20:17
  • That seems to fix it, at least value is not nil, but now I am getting the following error: bad argument #1 to 'say' (non-array table found). Can I not send it to say or did it not decode ? – Joel Parker Sep 10 '17 at 21:25
  • 1
    `say(cjson.encode(value))` – fefe Sep 10 '17 at 23:40
  • when I run the modified code value is nil ? Does anyone know why this is happening ? – Joel Parker Sep 11 '17 at 12:42
  • 1
    @fefe : `cjson.encode(value)` in my case gives`attempt to index global 'cjson' (a nil value)`... any easy fixes? – ntg Dec 03 '20 at 00:26

0 Answers0