local cjson = require("cjson.safe") -- 使用安全版
local data = {
name = "HGE引擎",
age = 18,
score = 99.5,
array = {1, 2, 3, 4, 5},
dict = {
name = "hello",
age = 20,
score = 10000
}
}
-- 编码并处理错误
local json_str, encode_err = cjson.encode(data)
if not json_str then
print("JSON Encode Error:", encode_err)
return
end
print(json_str)
-- 解码并处理错误
local json_table, decode_err = cjson.decode(json_str)
if not json_table then
print("JSON Decode Error:", decode_err)
return
end
-- 安全访问字段(假设字段可能存在)
print(json_table.name or "N/A")
print(json_table.age or 0)
print(json_table.score or 0)
print(json_table.array[1] or "No array data")
print(json_table.dict and json_table.dict.name or "No dict name") |