openresty开发系列25--openresty中使用json模块

web开发过程中,经常用的数据结构为json,openresty中封装了json模块,我们看如何使用

一)如何引入cjson模块,需要使用require
local json = require("cjson")

json.encode 将表格数据编码为 JSON 字符串
格式:
jsonString = json.encode(表格对象)
用法示例:

table 包含哈希键值对 和 数组键值对

-------------------test.lua--------------

1)table包含哈希键值对时,数组键值将被转换为字符串键值

local json = require("cjson")
local t = {1,3,name="张三",age="19",address={"地址1","地址2"},sex="女"}
ngx.say(json.encode(t));
ngx.say("<br/>");
----{"1":1,"2":3,"sex":"女","age":"19","address":["地址1","地址2"],"name":"张三"}

local str = json.encode({a=1,[5]=3})
ngx.say(str); ----- {"a":1,"5":3}
ngx.say("<br/>");

2)table所有键为数组型键值对时,会当作数组看待,空位将转化为null

local str = json.encode({[3]=1,[5]=2,[6]="3",[7]=4})
ngx.say(str); ---- [null,null,1,null,2,"3",4]
ngx.say("<br/>");

local str = json.encode({[3]=2,[5]=3})
ngx.say(str); ---- [null,null,2,null,3]
ngx.say("<br/>");

----------------------------------------

json.decode 将JSON 字符串解码为表格对象
格式:
table = json.decode(string)
用法示例:

local str  = [[ {"a":"v","b":2,"c":{"c1":1,"c2":2},"d":[10,11],"1":100} ]]
local t    = json.decode(str)
ngx.say(" --> ", type(t))

-------------

local str = [[ {"a":1,"b":null} ]]
local t    = json.decode(str)
ngx.say(t.a, "<br/>")  
ngx.say(t.b == nil, "<br/>")  
ngx.say(t.b == json.null, "<br/>")

----> 1
----> false
----> true

注意:null将会转换为json.null

二)异常处理

local json = require("cjson")
local str  = [[ {"key:"value"} ]]---少了一个双引号

local t    = json.decode(str)
ngx.say(" --> ", type(t))
执行请求,看看效果,执行报了--500 Internal Server Error
是因为decode方法报错了导致

实际情况我们希望的结果不是报错,而是返回一个友好的结果,如返回个nil

使用pcall命令
如果需要在 Lua 中处理错误,必须使用函数 pcall(protected call)来包装需要执行的代码。
pcall 接收一个函数和要传递给后者的参数,并执行,执行结果:有错误、无错误;
返回值 true 或者或 false, errorinfo。
pcall 以一种"保护模式"来调用第一个参数(函数),因此 pcall 可以捕获函数执行中的任何错误。

第一个方案:重新包装一个 json decode编码

local json = require("cjson")

local function _json_decode(str)
  return json.decode(str)
end

function json_decode( str )
    local ok, t = pcall(_json_decode, str)
    if not ok then
      return nil
    end

return t
end

local str  = [[ {"key:"value"} ]]---少了一个双引号

local t    = json_decode(str)
ngx.say(t)

执行效果,没有系统错误,返回了nil

第二个方案:引入cjson.safe 模块接口,该接口兼容 cjson 模块,并且在解析错误时不抛出异常,而是返回 nil。

local json = require("cjson.safe")
local str  = [[ {"key:"value"} ]]

local t    = json.decode(str)
if t then
    ngx.say(" --> ", type(t))
else
    ngx.say("t is nil")
end

三)空table返回object还是array

测试一下,编码空table   {}
local json = require("cjson")
ngx.say("value --> ", json.encode({}))
输出 value --> {}

{}是个object;对于java的开发人员来说就不对了,空数组table,应该是[]

这个是因为对于 Lua 本身,是把数组和哈希键值对融合到一起了,所以他是无法区分空数组和空字典的。

要达到目标把 encode_empty_table_as_object 设置为 false

local json = require("cjson")
json.encode_empty_table_as_object(false)
ngx.say("value --> ", json.encode({}))
输出 value --> []

openresty开发系列25--openresty中使用json模块的更多相关文章

  1. openresty开发系列36--openresty执行流程之6日志模块处理阶段

    openresty开发系列36--openresty执行流程之6日志模块处理阶段 一)header_filter_by_lua 语法:header_filter_by_lua <lua-scri ...

  2. openresty开发系列30--openresty中使用全局缓存

    openresty开发系列30--openresty中使用全局缓存 Nginx全局内存---本地缓存 使用过如Java的朋友可能知道如Ehcache等这种进程内本地缓存.Nginx是一个Master进 ...

  3. openresty开发系列29--openresty中发起http请求

    openresty开发系列29--openresty中发起http请求 有些场景是需要nginx在进行请求转发 用户浏览器请求url访问到nginx服务器,但此请求业务需要再次请求其他业务:如用户请求 ...

  4. openresty开发系列28--openresty中操作mysql

    openresty开发系列28--openresty中操作mysql Mysql客户端   应用中最常使用的就是数据库了,尤其mysql数据库,那openresty lua如何操作mysql呢?   ...

  5. openresty开发系列27--openresty中封装redis操作

    openresty开发系列27--openresty中封装redis操作 在关于web+lua+openresty开发中,项目中会大量操作redis, 重复创建连接-->数据操作-->关闭 ...

  6. openresty开发系列26--openresty中使用redis模块

    openresty开发系列26--openresty中使用redis模块 在一些高并发的场景中,我们常常会用到缓存技术,现在我们常用的分布式缓存redis是最知名的, 操作redis,我们需要引入re ...

  7. openresty开发系列24--openresty中lua的引入及使用

    openresty开发系列24--openresty中lua的引入及使用 openresty 引入 lua 一)openresty中nginx引入lua方式 1)xxx_by_lua   ---> ...

  8. openresty开发系列16--lua中的控制结构if-else/repeat/for/while

    openresty开发系列16--lua中的控制结构if-else/repeat/for/while 一)条件 - 控制结构 if-else if-else 是我们熟知的一种控制结构.Lua 跟其他语 ...

  9. openresty开发系列37--nginx-lua-redis实现访问频率控制

    openresty开发系列37--nginx-lua-redis实现访问频率控制 一)需求背景 在高并发场景下为了防止某个访问ip访问的频率过高,有时候会需要控制用户的访问频次在openresty中, ...

随机推荐

  1. 版本控制Git研究二

    经过好几周的工作忙碌,终于可以有时间静下心来学习东西了,做为崇尚技术的人来说,应该是最幸福的时光了,呵呵,当然也是宅神的表现啦,话不多说,继续git的学习,上次已经对git的一些概念进行了说明,具体可 ...

  2. springboot进行热部署项目

    百度了挺多的热部署,一种就是idea中一个插件,但是听说还需要 花钱,而且效果还是不太好. 自己按照网上的经验配置了一种属于自己的热部署,下面是详细的配置过程: 一.就是引入热部署需要的依赖: < ...

  3. 《代码敲不队》第九次团队作业:Beta冲刺第2天

    项目 内容 这个作业属于哪个课程 任课教师博客主页链接 这个作业的要求在哪里 作业链接地址 团队名称 代码敲不队 作业学习目标 (1)项目文档的完善与整理:(2)团队项目总结陈述PPT编制:(3)符合 ...

  4. c# 数据类型转换

    隐式转换 byte, short, int, long, fload, double等根据其顺序向后可以隐式自动完成类型的转换,隐式转移的前提是目标类型精度高于源类型,如:short隐式转换为int, ...

  5. 区别和认识.net四个判等方法

    概要 本方介绍.net如何判断两个对象是否相等 .Net有四个判等函数 1)Object.ReferenceEquals 2)Object.Equals 3)对象实例的Equals 4)==操作符 这 ...

  6. 浏览器兼容问题--get/post

    问题描述: 人员通过发送位置在百度地图上显示出来.删除人员后,chrome地图上该人员也随即消失,但IE浏览器上仍旧存在.清除缓存后,才消失. 原因: IE下面同一个地址,不会多次去请求的.只有加一个 ...

  7. HDU6072 Logical Chain

    题意:动态修改图 \(G\) 的边集,求每次修改后的 \(\sum c\times (c−1) / 2\) (记每个强连通分量中的点数量为 \(c\) ).其中修改操作共 \(m\) 次,每次最多改 ...

  8. 【EF】vs2017中没有EF模型

    在添加->新建项目 中找不到实体模型? 或者 在vs中打开edmx文件时,显示的只有文本,没有图形模式 原因:是因为没有安装实体模型插件 解决方法: 1.打开网址 https://marketp ...

  9. 【mysql】连接和断开服务器

    [mysql]连接和断开服务器 #启动服务: $sudo service mysql start #停止服务: $sudo service mysql stop 要连接到服务器,我们通常需要提供MyS ...

  10. PHP 鸟哥:我也曾经是“不适合”编程的人

    网名:雪候鸟,大家尊称鸟哥,惠新宸 @Laruence, 是国内最有影响力的 PHP 技术专家,PHP 开发组核心成员,PECL 开发者,Zend 公司外聘顾问.他曾供职于雅虎,百度,现在新浪微博任平 ...