You need to enable JavaScript to run this app. Python读取深度嵌套JSON中temperature字段的取值方法咨询
优惠活动
大模型
产品
解决方案
定价
更多

Python读取深度嵌套JSON中temperature字段的取值方法咨询

深度嵌套JSON取值的核心问题与解决方案

之前的写法错误根源

你取值失败的核心是没有区分JSON中的数组([])和对象({})类型:

  • weatherChannel 是数组而非直接包含week属性的对象,不能直接写 weatherChannel['week'],需要先取数组的第0项元素,才能访问内部的week属性。
  • 后续的 location、info 同样是数组结构,不是普通对象,不能直接在location上取info,需要先取数组的对应元素,再访问元素内部的属性。

可行的取值实现

假设你已经把JSON字符串解析成了JS对象,存在变量jsonData中,根据你的示例结构,有三类常用取值方式:

1. 确定所有层级都存在时的直接取值

完整取值链路逐层对应结构:
jsonData['weatherChannel'][0]['week']['location'][0]['info'][0]['temperature']
可直接运行的示例代码:

const jsonData = {
    "weatherChannel": [
       {
           "week": {
                "location": [
                    {
                        "info": [
                            {
                                "temperature": 5
                            }
                         ]
                     }
                 ]
            }
        }
     ]
}

// 直接取值,运行结果为5
const temperature = jsonData.weatherChannel[0].week.location[0].info[0].temperature;

2. 不确定层级完整性时的安全取值

如果线上数据可能出现数组为空、中间键缺失的情况,直接取值会抛出类型错误,可以用ES6可选链语法做容错,不会因为某一层缺失直接报错:

// 安全取值,任意一层缺失时返回undefined,不会抛出错误
const safeTemperature = jsonData?.weatherChannel?.[0]?.week?.location?.[0]?.info?.[0]?.temperature;

3. 数组存在多元素时的批量取值

如果weatherChannel、location这类数组可能包含多条数据,需要批量提取所有temperature值,可以用flatMap扁平化遍历:

// 提取所有嵌套在数组中的temperature值
const allTemperatures = jsonData.weatherChannel.flatMap(channel => 
    channel.week?.location?.flatMap(loc => 
        loc.info?.map(item => item.temperature) ?? []
    ) ?? []
);
// 示例结构下运行结果为 [5]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.18 02:57:01