如何遍历嵌套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
相关产品推荐
相关产品推荐

