OpenResty 中删除 json 中的转义符
cjson 在 encode 时 “/” 会自动添加转义符 “\”; 在 decode 时也会自动将转义符去掉。工作中有个特殊需求,需要手工删除转义符。记录备忘,代码如下:
#! /usr/bin/env lua
json = require "cjson" result = {}
result["stream"] = "lufei"
result["app"] = "live/cartoon" oldStr = json.encode(result)
local from, to, err = ngx.re.find(oldStr, [[\\]])
ngx.say(from, to)
newStr, n, err = ngx.re.gsub(oldStr, [[\\/]], [[/]])
ngx.say("oldStr: "..oldStr)
ngx.say("newStr: "..newStr ) t = json.decode(newStr)
ngx.say(t["app"])
dill@bunbun:~/openresty-test/locations$ curl -i localhost:/test
HTTP/1.1 OK
Server: openresty/1.11.2.2
Date: Wed, Jul :: GMT
Content-Type: text/plain
Transfer-Encoding: chunked
Connection: keep-alive oldStr: {"app":"live\/cartoon","stream":"lufei"}
newStr: {"app":"live/cartoon","stream":"lufei"}
live/cartoon