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

如何用Python3提取JSON中的@defaultTime特定元素?

提取Met Office JSON响应中@defaultTime字段的正确方法

你之前的代码返回None,是因为Timesteps字段并不直接在Layer节点下,而是嵌套在Service节点层级中。

正确的提取代码

使用完整的嵌套路径即可获取目标字段:

default_time = rain_forecast.get('Layers').get('Layer')[0].get('Service').get('Timesteps').get('@defaultTime')

容错优化建议

如果JSON结构存在字段缺失的可能,建议在链式get()调用中给中间节点设置默认值(比如空字典或空列表),避免触发AttributeError:

# 给可能缺失的节点设置默认值,增强代码健壮性
default_time = rain_forecast.get('Layers', {}).get('Layer', [{}])[0].get('Service', {}).get('Timesteps', {}).get('@defaultTime')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 15:18:57