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

如何解析cutoffTimes为对象而非数组结构的JSON数据

特殊结构JSON对象解析方案

问题原因

你当前的cutoffTimes字段是键为UUID、值为时间配置的普通对象,不是数组类型,因此没有内置的length属性,直接读取会返回undefined。

解决方案

1. 直接获取对象条目数量

如果你只需要获取数量,使用Object.keys()获取对象所有键的数组,再读取其长度即可:

// 注意原代码中JSON.parse({jsondoc})是语法错误,直接传入JSON字符串变量即可
let _times = JSON.parse(jsondoc);
const cutoffCount = Object.keys(_times.cutoffTimes).length;
console.log(`There are ${cutoffCount} times available`);

2. 转为数组方便后续操作

如果你后续需要遍历、处理每一条时间配置,推荐用Object.values()把对象的值直接转为数组,后续可以直接使用所有数组方法:

let _times = JSON.parse(jsondoc);
// 转换为普通数组,每个元素就是完整的时间配置对象
const cutoffTimeList = Object.values(_times.cutoffTimes);
console.log(`There are ${cutoffTimeList.length} times available`);

// 遍历示例:输出所有配置的时间
cutoffTimeList.forEach(config => {
  console.log(`ID: ${config.id},截止时间: ${config.time}`);
});

3. 同时获取键和值

如果需要用到外层的UUID键,可使用Object.entries()同时拿到键值对:

let _times = JSON.parse(jsondoc);
for (const [uuidKey, config] of Object.entries(_times.cutoffTimes)) {
  console.log(`UUID键: ${uuidKey},对应截止时间: ${config.time}`);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:06:04