使用for循环获取嵌套JSON指定值时遇TypeError问题求助
获取指定name对应的parentComponentId问题排查与解决
问题背景
需要编写Python函数get_parentcomponentid,从给定的JSON数据中找到powerPlant.name等于指定值的条目,返回其meta.parentComponentId。
原函数代码
def get_parentcomponentid(data, name): return next( element["parentComponentId"] for element in data for x in element["meta"] if x["name"] == name)
待处理的JSON数据
[ { 'powerPlant': { 'name': 'Nore 2', 'componentId': 7304, 'spotlessId': 11, 'timeSeries': None, 'units': [ { 'generatorName': 'Nore 2 G2', 'xyTimeSeries': None, 'componentId': 73042, 'timeSeries': None }, { 'generatorName': 'Nore 2 G1', 'xyTimeSeries': None, 'componentId': 73041, 'timeSeries': None } ] }, 'meta': { 'parentComponentId': 10024, 'technologyType': 'Hydro', 'regionId': 10, 'priceArea': 1 } }, { 'powerPlant': { 'name': 'Vinje', 'componentId': 7814, 'spotlessId': 19, 'timeSeries': None, 'units': [ { 'generatorName': 'Vinje G1', 'xyTimeSeries': None, 'componentId': 78141, 'timeSeries': None }, { 'generatorName': 'Vinje G3', 'xyTimeSeries': None, 'componentId': 78143, 'timeSeries': None }, { 'generatorName': 'Vinje G2', 'xyTimeSeries': None, 'componentId': 78142, 'timeSeries': None } ] }, 'meta': { 'parentComponentId': 10034, 'technologyType': 'Hydro', 'regionId': 10, 'priceArea': 2 } } ]
运行报错信息
return next( element["parentComponentId"] for element in data for x in element["meta"] > if x["name"] == name) E TypeError: string indices must be integers
用户疑问
是否是函数结构预期整数导致了这个错误?
问题分析与解决
错误原因
不是函数结构预期整数的问题,核心是对数据结构的理解错误:
element["meta"]是字典而非列表,用for x in element["meta"]遍历字典时,x会依次取字典的键(比如'parentComponentId'这类字符串)。- 此时执行
x["name"]相当于用字符串索引字符串,直接触发TypeError: string indices must be integers错误。 - 另外,目标
name实际存储在element["powerPlant"]["name"]中,而非meta结构里。
修正后的函数
def get_parentcomponentid(data, name): # 遍历条目,匹配powerPlant的name字段 return next( element["meta"]["parentComponentId"] for element in data if element["powerPlant"]["name"] == name , None) # 添加默认值,避免无匹配时抛出StopIteration异常
说明
- 直接遍历
data中的每个条目,检查powerPlant.name是否匹配目标值。 - 匹配成功时返回对应条目的
meta.parentComponentId。 - 给
next()添加第二个参数None,确保无匹配条目时返回None(可根据需求调整默认值)。
内容的提问来源于stack exchange,提问作者Magnus Jensen
相关产品推荐
相关产品推荐

