将 JSON 字符串转换为 Lua 表?

我需要将一个 Json 字符串转换为 Lua 中的表格数据结构。我正在使用以下代码。

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 )

但是当我运行脚本时,我会得到以下错误:

    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'

那么如何将我的 json 字符串转换为 Lua 表格呢?

点赞
用户1358661
用户1358661

也许lua-cjson是你的朋友:

例如通过luarocks安装:

$sudo luarocks install lua-cjson

然后在lua中:

local json = require('cjson')
local tab = json.decode(json_string)
json_string = json.encode(tab)
2014-07-25 06:34:09
用户3333438
用户3333438

你可以使用 json-lua。这是一个 JSON 的纯 Lua 实现。首先使用 Luarocks 安装 json-lua。luarocks install json-lua,然后使用如下代码:

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)

在 win 7 64 位与 Lua 5.1 上测试和验证。lua-cjson 也可以,但它不是纯 Lua 的。因此,它的安装对你来说可能不是那么容易。

2017-04-15 09:57:00