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

如何将REST接口返回结果存入数组变量并遍历ID?

实现方案

核心思路完全可行:你可以把JSON文件的内容解析后存入数组变量,再遍历提取ID。以下是几种常见语言的实现示例:

Python

import json

# 读取本地JSON文件并解析为数组变量
with open('data.json', 'r') as file:
    id_items = json.load(file)

# 遍历数组中的ID
for item in id_items:
    current_id = item['id']
    # 这里写入你的业务逻辑,比如打印、调用其他接口等
    print(current_id)

Node.js

const fs = require('fs');

// 读取JSON文件并解析
const rawData = fs.readFileSync('./data.json', 'utf8');
const idArray = JSON.parse(rawData);

// 遍历ID
idArray.forEach(item => {
    const currentId = item.id;
    // 替换为你的处理逻辑
    console.log(currentId);
});

Bash(依赖jq工具)

如果用命令行处理,先确保安装了jq,然后可以这样操作:

# 将所有ID存入bash数组
id_list=($(jq -r '.[].id' data.json))

# 遍历数组
for id in "${id_list[@]}"; do
    # 这里写你的处理命令
    echo "$id"
done

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 13:34:54