我正在尝试解析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}的值将成为字典中的键-例如顶级词典的locationIdname等。

如果您对“ children”子对象的“ 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

关于json - Robot Framework-TypeError:解析Json时,字符串索引必须为整数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53392257/

10-11 16:28