搜索
查看: 431|回复: 75

lua-cjson库

[复制链接]
回帖奖励 90 金钱 回复本帖可获得 18 金钱奖励! 每人限 2 次(中奖概率 80%)
发表于 2025-2-6 21:55:06 | 显示全部楼层 |阅读模式
local cjson = require("cjson")

local json_str = cjson.encode({
    name = "HGE引擎",
    age = 18,
    score = 99.5,
    array = {1, 2, 3, 4, 5},
    dict = {
        name = "hello",
        age = 20,
        score = 10000
    }
})

print(json_str)  -- 输出 {"name":"HGE引擎","age":18,"score":99.5,"array":[1,2,3,4,5],"dict":{"name":"hello","age":20,"score":10000}}

local json_table = cjson.decode(json_str)

print(json_table.name)  -- 输出 HGE引擎
print(json_table.age)  -- 输出 18
print(json_table.score)  -- 输出 99.5
print(json_table.array[1])  -- 输出 1
print(json_table.dict.name)  -- 输出 hello


本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
发表于 2025-2-7 00:03:59 | 显示全部楼层

回帖奖励 +18 金钱

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")
发表于 2025-2-7 01:45:08 | 显示全部楼层

回帖奖励 +18 金钱

回复本帖可获得 18 金钱奖励! 每人限 2 次(中奖概率 80%)
发表于 2025-2-7 07:10:51 | 显示全部楼层

回帖奖励 +18 金钱


回复本帖可获得 18 金钱奖励! 每人限 2 次(中奖概率 80%)
发表于 2025-2-7 07:11:40 | 显示全部楼层

回帖奖励 +18 金钱


回复本帖可获得 18 金钱奖励! 每人限 2 次(中奖概率 80%)
发表于 2025-2-7 08:37:28 | 显示全部楼层

回帖奖励 +18 金钱

回复本帖可获得 18 金钱奖励! 每人限 2 次(中奖概率 80%)
发表于 2025-2-7 08:37:44 | 显示全部楼层
回复本帖可获得 18 金钱奖励! 每人限 2 次(中奖概率 80%)
发表于 2025-2-7 08:38:16 | 显示全部楼层

回帖奖励 +18 金钱

回复本帖可获得 18 金钱奖励! 每人限 2 次(中奖概率 80%)
发表于 2025-2-7 08:48:50 | 显示全部楼层

回帖奖励 +18 金钱


回复本帖可获得 18 金钱奖励! 每人限 2 次(中奖概率 80%)
发表于 2025-2-7 08:49:22 | 显示全部楼层

回帖奖励 +18 金钱


回复本帖可获得 18 金钱奖励! 每人限 2 次(中奖概率 80%)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|HGEM2论坛

GMT+8, 2025-2-21 20:40 , Processed in 0.477514 second(s), 15 queries .

Powered by Discuz! X3.4

Copyright © 2001-2023, Tencent Cloud.

快速回复 返回顶部 返回列表