cjson 解析{ "name": "sys", "type": "table", "data": [ { "name": "dbc_path", "type": "string", "data": "/usrdata/dbc/GB-EP40_CAN_r5_v1.0.dbc" }, { "name": "first_boot", "type": "unsigned", "data": "0" }, { "name": "configNet", "type": "group", "data": [ { "name": "privateApnAddress", "type": "string", "data": "www.qq.com" }, { "name": "publicApnAddress", "type": "string", "data": "172.0.0.1" }, { "name": "publicApnUserName", "type": "string", "data": "172.0.0.1" }, { "name": "publicApnPassword", "type": "string", "data": "172.0.0.1" }, { "name": "publicDnsAddress", "type": "string", "data": "172.0.0.1" }, { "name": "publicDNsAddressBak", "type": "string", "data": "172.0.0.1" } ] } ] }
时间: 2023-07-07 13:45:03 浏览: 110
cJSON解析json数据
5星 · 资源好评率100%
你可以使用 Lua 的 cjson 库来解析该 JSON 字符串,示例代码如下:
```lua
local cjson = require("cjson")
-- JSON 字符串
local jsonStr = [[
{
"name": "sys",
"type": "table",
"data": [
{
"name": "dbc_path",
"type": "string",
"data": "/usrdata/dbc/GB-EP40_CAN_r5_v1.0.dbc"
},
{
"name": "first_boot",
"type": "unsigned",
"data": "0"
},
{
"name": "configNet",
"type": "group",
"data": [
{
"name": "privateApnAddress",
"type": "string",
"data": "www.qq.com"
},
{
"name": "publicApnAddress",
"type": "string",
"data": "172.0.0.1"
},
{
"name": "publicApnUserName",
"type": "string",
"data": "172.0.0.1"
},
{
"name": "publicApnPassword",
"type": "string",
"data": "172.0.0.1"
},
{
"name": "publicDnsAddress",
"type": "string",
"data": "172.0.0.1"
},
{
"name": "publicDNsAddressBak",
"type": "string",
"data": "172.0.0.1"
}
]
}
]
}
]]
-- 解析 JSON 字符串
local jsonObj = cjson.decode(jsonStr)
-- 打印解析结果
print(jsonObj.name) -- 输出 sys
print(jsonObj.type) -- 输出 table
-- 遍历 data 数组
for i, item in ipairs(jsonObj.data) do
print(item.name, item.type, item.data)
if item.type == "group" then
-- 遍历子元素
for j, subItem in ipairs(item.data) do
print(" ", subItem.name, subItem.type, subItem.data)
end
end
end
```
输出结果为:
```
sys
table
dbc_path string /usrdata/dbc/GB-EP40_CAN_r5_v1.0.dbc
first_boot unsigned 0
configNet group
privateApnAddress string www.qq.com
publicApnAddress string 172.0.0.1
publicApnUserName string 172.0.0.1
publicApnPassword string 172.0.0.1
publicDnsAddress string 172.0.0.1
publicDNsAddressBak string 172.0.0.1
```
阅读全文