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

如何遍历服务器返回JSON中instances对象内的演出日期?

遍历存储instances对象中的日期字段

嘿,我懂你遇到的这个小麻烦了——服务器返回的JSON里instances是个以日期为键的对象,而不是咱们习惯遍历的数组,常规的数组遍历方法直接用不了,对吧?别担心,我给你几个常用编程语言的解决方案,你按需取用就行~

JavaScript 实现

你可以用Object.keys()方法提取instances对象的所有日期键,之后就能轻松遍历存储了:

// 假设你已经将服务器响应解析为JSON对象
const responseData = { 
  "data": [ 
    { 
      "id": "XYFYyvu2bckt", 
      "theater_id": "clzEVgztkcWB", 
      "theater_audi_id": "N9iDgooiCW6N", 
      "movie_lang_id": "B9x98d4IEpCt", 
      "booking_start_date": null, 
      "instances": { 
        "2018-04-18": [ { "id": "vpcr2c..." } ],
        "2018-04-19": [ { "id": "abc123..." } ]
      } 
    } 
  ] 
};

// 遍历data数组中的每一项(如果有多个演出项的话)
responseData.data.forEach(showItem => {
  // 提取当前演出的instances对象
  const instances = showItem.instances;
  // 获取所有日期键
  const showDates = Object.keys(instances);
  
  // 遍历日期并执行存储逻辑
  showDates.forEach(date => {
    console.log(`准备存储日期: ${date}`);
    // 这里替换成你的存储代码,比如存入数组、数据库等
    // 如果需要获取该日期对应的场次数据,可以用 instances[date]
  });
});

Python 实现

Python的字典本身支持直接遍历键,处理起来更直观:

import json

# 假设你拿到了服务器返回的JSON字符串
response_str = '''{ 
  "data": [ 
    { 
      "id": "XYFYyvu2bckt", 
      "theater_id": "clzEVgztkcWB", 
      "theater_audi_id": "N9iDgooiCW6N", 
      "movie_lang_id": "B9x98d4IEpCt", 
      "booking_start_date": null, 
      "instances": { 
        "2018-04-18": [ { "id": "vpcr2c..." } ],
        "2018-04-19": [ { "id": "abc123..." } ]
      } 
    } 
  ] 
}'''

# 将JSON字符串解析为Python字典
response_data = json.loads(response_str)

# 遍历data数组中的每个演出项
for show_item in response_data['data']:
    # 获取当前演出的instances字典
    instances = show_item['instances']
    # 遍历所有日期键
    for date in instances.keys():
        print(f"准备存储日期: {date}")
        # 这里添加你的存储逻辑
        # 如需获取对应场次数据,可使用 instances[date]

补充说明

如果你的data数组里包含多个演出条目,一定要记得先遍历data数组,再处理每个条目下的instances对象,这样就不会漏掉任何一个演出的日期啦~

内容的提问来源于stack exchange,提问作者Rishabh.t

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:57:34