Lua json使用
版本
Lua 5.3
编码与解码
-- cjson.encode 是用于编码,将 lua 值转换为 json 字符串;
-- cjson.decode 是用于解码,将 json 字符串转换为 lua 值;
local cjson = require("json")
-- 编码
elite_print("encode test")
-- 布尔类型
local lua_bool = true
sleep(2)
elite_print(cjson.encode(lua_bool))
-- 数组类型
local lua_array = {1, 2, 3, 4, 5, 6}
sleep(2)
elite_print(cjson.encode(lua_array))
-- 数值类型
local lua_number = 6.66
sleep(2)
elite_print(cjson.encode(lua_number))
-- 字符串类型
local lua_string = "I am test 1280"
sleep(2)
elite_print(cjson.encode(lua_string))
-- 对象类型
local lua_object = {
["name"] = "Jiang",
["age"] = 24,
["addr"] = "BeiJing",
["email"] = "XXX@126.com",
["tel"] = "139XXX"
}
sleep(2)
elite_print(cjson.encode(lua_object))
-- 解码
sleep(2)
elite_print("decode test")
-- 布尔类型
local json_bool = "false"
local lua_json = cjson.decode(json_bool)
sleep(2)
elite_print(type(lua_json))
-- 数组类型
local json_array = "[9,8,7,6,5,4,3,2,1]"
local lua_array = cjson.decode(json_array)
sleep(2)
elite_print(type(lua_array), #lua_array)
--[[
if (type(lua_array) == "table") then
for i, val in ipairs(lua_array) do
sleep(1)
elite_print(i,val)
end
end
--]]
-- 数值类型
local json_number = "666.66"
local lua_number = cjson.decode(json_number)
elite_print(type(lua_number), lua_number)
-- 字符串类型
local json_string = "\"I am test1280\""
local lua_string = cjson.decode(json_string)
elite_print(type(lua_string),lua_string)
-- 对象类型
local json_object = "{\"name\":\"Jiang\",\"age\":24,\"addr\":\"BeiJing\",\"email\":\"XXX@126.com\",\"tel\":\"139XXX\"}"
local lua_object = cjson.decode(json_object)
elite_print(type(lua_object))
---[[
for k, v in pairs(lua_object) do
sleep(1)
elite_print(k,v)
end
--]]
local array = {}
array[1] = 1
array[6] = 6
array[9] = 9
array["name"] = "test1280"
sleep(1)
elite_print(cjson.encode(array))
来源:https://blog.csdn.net/yyjbluesword/article/details/100526748