欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Lua利用cjson读写json示例分享

程序员文章站 2022-08-29 09:18:54
我这里采用的是lua cjson库,是一个高性能的json解析器和编码器,其性能比纯lua库要高10~20倍。并且lua json完全支持utf-8,无需以来其他非lua/...

我这里采用的是lua cjson库,是一个高性能的json解析器和编码器,其性能比纯lua库要高10~20倍。并且lua json完全支持utf-8,无需以来其他非lua/luajit相关包。

环境安装

这里就不详细写了,随便问下谷歌就有一大堆答案。

示例代码

解析json

复制代码 代码如下:

local cjson = require "cjson"
local samplejson = [[{"age":"23","testarray":{"array":[8,9,11,14,25]},"himi":"himigame.com"}]];
--解析json字符串
local data = cjson.decode(samplejson);
--打印json字符串中的age字段
print(data["age"]);
--打印数组中的第一个值(lua默认是从0开始计数)
print(data["testarray"]["array"][1]);  

编码json

复制代码 代码如下:

local cjson = require "cjson"
local rettable = {};    --最终产生json的表
--顺序数值
local intdatas = {};
intdatas[1] = 100;
intdatas[2] = "100";
--数组
local arydatas = {};
arydatas[1] = {};
arydatas[1]["键11"] = "值11";
arydatas[1]["键12"] = "值12";
arydatas[2] = {};
arydatas[2]["键21"] = "值21";
arydatas[2]["键22"] = "值22";
--对table赋值
rettable["键1"] = "值1";
rettable[2] = 123;
rettable["int_datas"] = intdatas;
rettable["arydatas"] = arydatas;
--将表数据编码成json字符串
local jsonstr = cjson.encode(rettable);
print(jsonstr);
--结果是:{"int_datas":[100,"100"],"2":123,"键1":"值1","arydatas":[{"键12":"值12","键11":"值11"},{"键21":"值21","键22":"值22"}]}

写在最后

以上只是对于cjson库的简单应用示例,如有任何问题请及时给我留言。