OpenResty json 删除转义符
2017-07-19 12:48 DillGao 阅读(1479) 评论(0) 编辑 收藏 举报OpenResty 中删除 json 中的转义符
cjson 在 encode 时 “/” 会自动添加转义符 “\”; 在 decode 时也会自动将转义符去掉。工作中有个特殊需求,需要手工删除转义符。记录备忘,代码如下:
1 #! /usr/bin/env lua 2 json = require "cjson" 3 4 result = {} 5 result["stream"] = "lufei" 6 result["app"] = "live/cartoon" 7 8 oldStr = json.encode(result) 9 local from, to, err = ngx.re.find(oldStr, [[\\]]) 10 ngx.say(from, to) 11 newStr, n, err = ngx.re.gsub(oldStr, [[\\/]], [[/]]) 12 ngx.say("oldStr: "..oldStr) 13 ngx.say("newStr: "..newStr ) 14 16 t = json.decode(newStr) 17 ngx.say(t["app"])
dill@bunbun:~/openresty-test/locations$ curl -i localhost:6699/test HTTP/1.1 200 OK Server: openresty/1.11.2.2 Date: Wed, 19 Jul 2017 04:38:07 GMT Content-Type: text/plain Transfer-Encoding: chunked Connection: keep-alive 1313 oldStr: {"app":"live\/cartoon","stream":"lufei"} newStr: {"app":"live/cartoon","stream":"lufei"} live/cartoon