Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON String to Lua Table?

Tags:

json

lua

I need to convert a Json String to a table data structure in Lua. I am using the following code.

local json = require "json"

local t = { 
    ["name1"] = "value1",
    ["name2"] = { 1, false, true, 23.54, "a \021 string" },
    name3 = json.null
}

local encode = json.encode (t)
print (encode)  --> {"name1":"value1","name3":null,"name2":[1,false,true,23.54,"a \u0015 string"]}

local decode = json.decode( encode )

But when I run the script, I get the following errors,

    no field package.preload['json']
    no file '/usr/local/share/lua/5.2/json.lua'
    no file '/usr/local/share/lua/5.2/json/init.lua'
    no file '/usr/local/lib/lua/5.2/json.lua'
    no file '/usr/local/lib/lua/5.2/json/init.lua'
    no file './json.lua'
    no file '/usr/local/lib/lua/5.2/json.so'
    no file '/usr/local/lib/lua/5.2/loadall.so'
    no file './json.so'

So how to convert my json string to lua table?

like image 898
user3213851 Avatar asked Jul 23 '14 10:07

user3213851


1 Answers

maybe lua-cjsonis your friend:

install e.g. through luarocks:

$sudo luarocks install lua-cjson

then in lua:

local json = require('cjson')
local tab = json.decode(json_string)
json_string = json.encode(tab)
like image 122
lipp Avatar answered Sep 28 '22 08:09

lipp