第五章 常用Lua开发库2-JSON库、编码转换、字符串处理

Lua  /  houtizong 发布于 3年前   247

 

JSON库

 

在进行数据传输时JSON格式目前应用广泛,因此从Lua对象与JSON字符串之间相互转换是一个非常常见的功能;目前Lua也有几个JSON库,本人用过cjson、dkjson。其中cjson的语法严格(比如unicode \u0020\u7eaf),要求符合规范否则会解析失败(如\u002),而dkjson相对宽松,当然也可以通过修改cjson的源码来完成一些特殊要求。而在使用dkjson时也没有遇到性能问题,目前使用的就是dkjson。使用时要特别注意的是大部分JSON库都仅支持UTF-8编码;因此如果你的字符编码是如GBK则需要先转换为UTF-8然后进行处理。

1.1、test_cjson.lua

local cjson = require("cjson")--lua对象到字符串local obj = {    id = 1,    name = "zhangsan",    age = nil,    is_male = false,    hobby = {"film", "music", "read"}}local str = cjson.encode(obj)ngx.say(str, "<br/>")--字符串到lua对象str = '{"hobby":["film","music","read"],"is_male":false,"name":"zhangsan","id":1,"age":null}'local obj = cjson.decode(str)ngx.say(obj.age, "<br/>")ngx.say(obj.age == nil, "<br/>")ngx.say(obj.age == cjson.null, "<br/>")ngx.say(obj.hobby[1], "<br/>")--循环引用obj = {   id = 1}obj.obj = obj-- Cannot serialise, excessive nesting--ngx.say(cjson.encode(obj), "<br/>")local cjson_safe = require("cjson.safe")--nilngx.say(cjson_safe.encode(obj), "<br/>")
null将会转换为cjson.null;循环引用会抛出异常Cannot serialise, excessive nesting,默认解析嵌套深度是1000,可以通过cjson.encode_max_depth()设置深度提高性能;使用cjson.safe不会抛出异常而是返回nil。 

 

1.2、example.conf配置文件

     location ~ /lua_cjson {        default_type 'text/html';        lua_code_cache on;        content_by_lua_file /usr/example/lua/test_cjson.lua;     }
 

1.3、访问如http://192.168.1.2/lua_cjson将得到如下结果

{"hobby":["film","music","read"],"is_male":false,"name":"zhangsan","id":1}nullfalsetruefilmnil

 

lua-cjson文档http://www.kyne.com.au/~mark/software/lua-cjson-manual.html

 

接下来学习下dkjson。

 

2.1、下载dkjson库 

cd /usr/example/lualib/wget http://dkolf.de/src/dkjson-lua.fsl/raw/dkjson.lua?name=16cbc26080996d9da827df42cb0844a25518eeb3 -O dkjson.lua

 

2.2、test_dkjson.lua

local dkjson = require("dkjson")--lua对象到字符串local obj = {    id = 1,    name = "zhangsan",    age = nil,    is_male = false,    hobby = {"film", "music", "read"}}local str = dkjson.encode(obj, {indent = true})ngx.say(str, "<br/>")--字符串到lua对象str = '{"hobby":["film","music","read"],"is_male":false,"name":"zhangsan","id":1,"age":null}'local obj, pos, err = dkjson.decode(str, 1, nil)ngx.say(obj.age, "<br/>")ngx.say(obj.age == nil, "<br/>")ngx.say(obj.hobby[1], "<br/>")--循环引用obj = {   id = 1}obj.obj = obj--reference cycle--ngx.say(dkjson.encode(obj), "<br/>")                                     
默认情况下解析的json的字符会有缩排和换行,使用{indent = true}配置将把所有内容放在一行。和cjson不同的是解析json字符串中的null时会得到nil。   

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客