Lua 解析 JSON 字符串:cjson 和 dkjson 库使用指南
在 Lua 中解析 JSON 字符串需要使用第三方库。常用的解析库有 cjson 和 dkjson。
使用 cjson 库解析 JSON 字符串
local cjson = require("cjson")
local jsonStr = '{"name": "John", "age": 30, "city": "New York"}'
-- 解析 JSON 字符串
local jsonData = cjson.decode(jsonStr)
-- 访问 JSON 数据
print(jsonData.name) -- 输出:John
print(jsonData.age) -- 输出:30
print(jsonData.city) -- 输出:New York
使用 dkjson 库解析 JSON 字符串
local dkjson = require("dkjson")
local jsonStr = '{"name": "John", "age": 30, "city": "New York"}'
-- 解析 JSON 字符串
local jsonData = dkjson.decode(jsonStr)
-- 访问 JSON 数据
print(jsonData.name) -- 输出:John
print(jsonData.age) -- 输出:30
print(jsonData.city) -- 输出:New York
这两个库的使用方法基本一致,你可以根据自己的需求选择其中一个使用。
原文地址: http://www.cveoy.top/t/topic/qyac 著作权归作者所有。请勿转载和采集!