我正在尝试解析一组 json,但出现以下错误
TypeError: string indices must be integers
杰森:
{
'locationId': 'location1',
'name': 'Name',
'type': 'Ward',
'patientId': None,
'children': [{
'locationId': 'location2',
'name': 'Name',
'type': 'Bed',
'patientId': None,
'children': [{
'locationId': 'location3',
'name': 'Name',
'type': 'HospitalGroup',
'patientId': None,
'children': None
}]
}, {
'locationId': 'location4',
'name': 'Name',
'type': 'Hospital',
'patientId': None,
'children': None
}, {
'locationId': 'location5',
'name': 'Name',
'type': 'Bed',
'patientId': None,
'children': None
}, {
'locationId': 'location6',
'name': 'Name',
'type': 'Bed',
'patientId': None,
'children': None
}, {
'locationId': 'location27',
'name': 'Name',
'type': 'Bed',
'patientId': None,
'children': None
}]
}
我正在尝试获取所有 locationId 值并将这些值一一存储在列表中。
这是我在做什么
@{locationIds}= create list
:FOR ${item} IN @{Location_Json}
\ ${locationId}= set variable ${item['locationId']}
\ log ${locationId}
\ append to list ${locationIds} '${locationId}'
我也试过这个
@{locationIds}= create list
:FOR ${item} IN @{Location_Json}
\ ${locationId}= set variable ${item['children'][0]['locationId']}
\ log ${locationId}
\ append to list ${locationIds} '${locationId}'
但我遇到了同样的错误。
这条线上的测试失败 ${locationId}= set variable ${item['locationId']}
任何帮助都会受到赞赏。
如果 var 的内容${Location_Json}
确实是您上面放置的 json 示例,则可以解释异常“字符串索引必须是整数”。
您正在使用的 json 是字典(不是列表);因此,在这个循环中:
:FOR ${item} IN @{Location_Json}
,价值${item}
将是该键在字典中的-例如locationId
,name
等顶级字典。
如果您对“children” subdict 的“locationId”感兴趣,那就可以了 - 迭代“children”项:
:FOR ${item} IN @{Location_Json['children']}
在每次迭代中,${item}
它将成为“children”中的子字典之一,您可以获得它的“locationId”
\ ${locationId}= set variable ${item['locationId']}
与您的问题无关,请不要这样做:
append to list ${locationIds} '${locationId}'
不要将 的值${locationId}
放在单引号内 - 会发生的是这些引号现在将成为列表成员的一部分。
说,值${locationId}
是
location5
加上周围的引号,它最终会变成
'location5'
我不认为那是你的目标;使用这些额外的引号,这将失败:
Should Be Equal As Strings location5 ${locationIds[3]} # because locationIds[3] will have the extra quotes
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句