Lua: JSON encode and decode


Method 1: use lua-cjson

luarocks install lua-cjson

Result:

[root@tutorialspots ~]# luarocks install lua-cjson
Installing https://luarocks.org/lua-cjson-2.1.0.6-1.src.rock
gcc -O2 -fPIC -I/usr/local/include/luajit-2.1 -c lua_cjson.c -o lua_cjson.o
gcc -O2 -fPIC -I/usr/local/include/luajit-2.1 -c strbuf.c -o strbuf.o
gcc -O2 -fPIC -I/usr/local/include/luajit-2.1 -c fpconv.c -o fpconv.o
gcc -shared -o cjson.so -L/usr/local/lib lua_cjson.o strbuf.o fpconv.o
No existing manifest. Attempting to rebuild...
lua-cjson 2.1.0.6-1 is now installed in /usr/local (license: MIT)

Example:

local json_string = "{\"website\":\"www.tutorialspots.com\"}"
local json = require('cjson')
local tab = json.decode(json_string)
json_string = json.encode(tab)
print(json_string)

Result:

{"website":"www.tutorialspots.com"}

Online demo: Here

Method 2: use json4lua

wget -q https://raw.githubusercontent.com/Egor-Skriptunoff/json4lua/master/json.lua -O /usr/local/lib/lua/resty/json.lua

Example:

local json_string = "{\"website\":\"www.tutorialspots.com\"}"
local json = require('json')
local tab = json.decode(json_string)
json_string = json.encode(tab)
print(json_string)

Method 3: use json.lua

wget -q https://raw.githubusercontent.com/rxi/json.lua/master/json.lua -O /usr/local/lib/lua/resty/json.lua

Leave a Reply