You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Lua脚本中读取并遍历请求体中的对象数组

Lua处理JSON中的TheatreInfo对象数组

假设你已经将JSON请求体解析为Lua table body(通常可通过cjson库完成解析,示例代码见下文),以下是几种处理TheatreInfo数组的常见方式:

1. 基础解析与访问

先确保JSON已转换为Lua可操作的table:

local cjson = require("cjson")
-- 假设request_body是原始JSON字符串
local body = cjson.decode(request_body)

直接访问数组中的单个元素:

-- 获取第一个影院的信息
local first_theatre = body["TheatreInfo"][1]
print("第一个影院ID:" .. first_theatre.tId)
print("第一个影院名称:" .. first_theatre.tname)

2. 将数组整合到transform_body中

如果需要把TheatreInfo数组处理后加入你的transform_body,可遍历数组并按需调整结构:

local transform_body = {}
transform_body["year"] = body["year"]
transform_body["languageid"] = body["languageId"]
transform_body["city"] = body["city"]

-- 初始化处理后的影院数组
transform_body["theatre_info"] = {}

-- 遍历原数组,处理每个影院对象
for _, theatre in ipairs(body["TheatreInfo"]) do
    -- 可根据需求修改键名或提取特定字段
    local processed_theatre = {
        theatre_id = theatre["tId"],
        theatre_name = theatre["tname"]
    }
    table.insert(transform_body["theatre_info"], processed_theatre)
end

-- 若无需修改结构,直接复制原数组即可:
-- transform_body["theatre_info"] = body["TheatreInfo"]

3. 遍历数组执行自定义逻辑

如果需要对每个影院信息执行额外操作(如校验、打印),可通过循环遍历实现:

for idx, theatre in ipairs(body["TheatreInfo"]) do
    print(string.format("影院%d:ID=%s,名称=%s", idx, theatre.tId, theatre.tname))
    -- 此处可添加其他逻辑,比如校验tId格式是否合法
end

4. 处理数组不存在的异常情况

为避免body["TheatreInfo"]为空或不存在导致报错,建议增加前置判断:

transform_body["theatre_info"] = {}
if body["TheatreInfo"] and type(body["TheatreInfo"]) == "table" then
    for _, theatre in ipairs(body["TheatreInfo"]) do
        local processed_theatre = {
            theatre_id = theatre["tId"],
            theatre_name = theatre["tname"]
        }
        table.insert(transform_body["theatre_info"], processed_theatre)
    end
end

内容的提问来源于stack exchange,提问作者Chandu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 06:33:20