将 JSON 字符串转换为 Lua 表? [英] Convert JSON String to Lua Table?
本文介绍了将 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 21 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 是你的朋友:
安装例如通过 luarocks:
install e.g. through luarocks:
$sudo luarocks install lua-cjson
然后在lua中:
local json = require('cjson')
local tab = json.decode(json_string)
json_string = json.encode(tab)
这篇关于将 JSON 字符串转换为 Lua 表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文