openresty 前端 開發 入門 json 欄目 JavaScript 简体版
原文   原文鏈接

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

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

lua/hello.luagithub

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字符串web

示例代碼 參見demo3部分json

相關文章
相關標籤/搜索
每日一句
    每一个你不满意的现在,都有一个你没有努力的曾经。
本站公眾號
   歡迎關注本站公眾號,獲取更多信息