Openresty front-end development entry three JSON articles

#### This chapter mainly introduces how lua returns a json string, how to convert a table into a json string, and how to convert a json string into json

. It is actually very simple to use the encode, The decode method can be

lua/hello.lua
```
local cjson = require "cjson"

-- first define a json string
local json_str = '{"name": "Bruce.Lin", "age": 25}'
- - Convert it to an object here, and output the property
local json = cjson.decode(json_str)
ngx.say("Name = " .. json['name'] .. ", Age = " .. tostring(json[' age'])) -- here you need to convert 25 into a string to perform string splicing

-- output Name = Bruce.Lin, Age = 25

ngx.say('<br/>') -- newline

-- connect Next, let's convert the json object into a json string
local json_str2 = cjson.encode(json)
ngx.say(json_str2)

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

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

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

ngx.say(cjson.encode(obj))

ngx.say('<br/>') -- newline

local obj2 = {}

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

ngx.say(cjson.encode(obj2))

```

ok, here we will learn the json string

[sample code](https://github.com/362228416/openresty -web-dev) see demo3 section

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326382930&siteId=291194637