文章出處

這章主要介紹一下,lua怎么返回一個json字符串,怎么把一個table轉成json字符串,又怎么把一個json字符串轉成json

其實很簡答,直接使用cjson庫的encode、decode方法即可

lua/hello.lua

local cjson = require "cjson"

-- 先定義一個json字符串
local json_str = '{"name": "Bruce.Lin", "age": 25}'
-- 這里把它轉成對象,然后輸出屬性
local json = cjson.decode(json_str)
ngx.say("Name = " .. json['name'] .. ", Age = " .. tostring(json['age'])) -- 這里需要把25轉成字符串,才能進行字符串拼接

-- 輸出 Name = Bruce.Lin, Age = 25

ngx.say('<br/>') -- 換行

-- 接下來我們再把json對象轉成json字符串
local json_str2 = cjson.encode(json)
ngx.say(json_str2)

-- 輸出{"name":"Bruce.Lin","age":25}

ngx.say('<br/>') -- 換行

local obj = {
    ret = 200,
    msg = "login success"
}

ngx.say(cjson.encode(obj))

ngx.say('<br/>') -- 換行

local obj2 = {}

obj2['ret'] = 200
obj2['msg'] = "login fails"

ngx.say(cjson.encode(obj2))

ok,這里我們就學會的json字符串

示例代碼 參見demo3部分


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()