Search code examples
nginxluacjson

Get json value in lua using cjson


I have a json string encoded using json in lua for nginx. I have used cjson for encoding I need to get value of a json key.

{
  "key1": "value1",
  "key2": value2,
  "content": {
    "key4": "value4"
    }
}
}

How to get the value of key4 in lua.

So i have following

local encodedjson = cjson.encode(jwt_obj)

How do i extract value4 from encodedjson variable.


Solution

  • The Lua cjson library can take a JSON string and convert it into a Lua table using cjson.decode.

    Once you have decoded the JSON string you can index the table with the keys. json_table.content.key4

    Please note that numeric keys in a JSON file will always be represented as a string key in a lua table

    i.e: t['1'] not t[1]

    References: Lua CJSON: 3.3 decode