将JSON字符串转换为Lua表吗? [英] Convert JSON String to Lua Table?

查看:1552
本文介绍了将JSON字符串转换为Lua表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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'

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

So how to convert my json string to lua table?

推荐答案

也许 lua-cjson 是您的朋友:

安装例如通过羽绒被:

$sudo luarocks install lua-cjson

然后在lua:

local json = require('cjson')
local tab = json.decode(json_string)
json_string = json.encode(tab)

这篇关于将JSON字符串转换为Lua表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆