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

如何遍历嵌套JSON并提取指定字段'l'的值到列表?

如何从嵌套JSON中提取指定字段'l'到列表?

我看了你的问题和代码,问题出在循环里的取值逻辑上——你的JSON最外层是一个以"123abc"这类字符串为键的字典,每个键对应的值才是包含"l"字段的子字典,而你直接写data["l"]是在最外层字典里找"l"这个键,自然会触发KeyError。

修正基础循环代码

只需要把循环里的取值方式改成从每个键对应的子字典里取"l"即可:

import json

with open("daydreamer-b8036-all-export (1).json", "r") as read_file:
    data = json.load(read_file)

locationList = []
for key in data:
    # 先拿到当前键对应的子字典,再从中提取'l'字段
    value = data[key]["l"]
    locationList.append(value)

print(locationList)

更简洁的列表推导式写法

如果你想简化代码,可以用Python的列表推导式,一行就能生成目标列表:

import json

with open("daydreamer-b8036-all-export (1).json", "r") as read_file:
    data = json.load(read_file)

locationList = [item["l"] for item in data.values()]
print(locationList)

这里直接遍历data.values(),拿到每个子字典,再提取"l"字段,比循环append更高效简洁。

用Pandas处理的方式

既然你导入了Pandas,也可以用json_normalize来扁平化数据,再提取目标字段:

import json
import pandas as pd
from pandas.io.json import json_normalize

with open("daydreamer-b8036-all-export (1).json", "r") as read_file:
    data = json.load(read_file)

# 把外层字典转成列表(每个元素是带原键的字典),再扁平化
df = json_normalize([{"id": k, **v} for k, v in data.items()])
# 提取'l'列转成列表
locationList = df["l"].tolist()
print(locationList)

这种方式适合后续还要对数据做更多分析的场景,能把嵌套JSON转成结构化的DataFrame。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 17:47:45