对于Robotframework,在给定的测试用例code 1
和code 2
中访问字典对象。问题是,当我使用json.load转换我的json对象返回一个列表时,返回单个'而不是双逗号'对象的json键,当我不使用json.load时,它返回Unicode错误
定义库
*** Settings ***
Library OperatingSystem
Library Collections
Library HttpLibrary.HTTP
*** Test Cases ***
Code1
#get json file
${json_data}= Get file detail.json
#get dictionaries under list
${valuelist}= Get Json Value ${json_data} /alladdress/addresslist
# display it
log to console ${valuelist}
# loop over dictionaries under list
: FOR ${key} in @{valuelist.keys()}
\ ${value}= Get From Dictionary ${valuelist} ${key}
# getting AttributeError: 'unicode' object has no attribute 'keys
\ log to console ${key},${value}
Code2
# get json file
${json_data}= Get file detail.json
# get dictionaries under list
${valuelist}= Get Json Value ${json_data} /alladdress/addresslist
# use below line to avoid unicode error
${obj_list}= evaluate json.loads('''${valuelist}''') json
# display it
log to console ${obj_list}
# loop over dictionaries under list
: FOR ${key} in @{obj_list.keys()}
\ ${value}= Get From Dictionary ${obj_list} ${key}
# getting AttributeError: 'list' object has no attribute 'keys'
\ log to console ${key},${value}
这里是 json文件
{
"class":{
"id":0,
"name":"David"
},
"alladdress":{
"count":3,
"addresslist":[
{
"houseno":1,
"streetno":5,
"streetname":"tesla",
"city":"ABC",
"state":"AA",
"country":"UK",
"zip":85555
},
{
"houseno":2,
"streetno":6,
"streetname":"honda",
"city":"PQR",
"state":"BB",
"country":"IN",
"zip":5252
}
]
}
}
答案 0 :(得分:1)
在HttpLibrary库中,此处有Parse JSON
关键字。它可以将使用Get JSON Value
获取的JSON文档的字符串转换为字典。
所以这里的值是你不必“走”字典去到你正在寻找的节点。
*** Settings ***
Library OperatingSystem
Library HttpLibrary.HTTP
*** Test Cases ***
Fetch Address List
${json_data}= Get file details.json
${addressesJSONstring} Get Json Value ${json_data} /alladdress/addresslist
${addresseslist} Parse Json ${addressesJSONstring}
: FOR ${addressDict} in @{addresseslist}
\ log ${addressDict['country']}
答案 1 :(得分:0)
关键字Get json value
似乎是返回字符串而不是对象。如果用使用python&#j; sson模块的代码替换该调用,则可以解析数据以找到所需内容。
例如,这将打印出每个地址字典:
*** Test Cases ***
Code1
#get json file
${json_data}= Get file detail.json
#get dictionaries under list
${data}= evaluate json.loads($json_data) json
${alladdress}= get from dictionary ${data} alladdress
${addresslist}= get from dictionary ${alladdress} addresslist
# loop over dictionaries under list
log to console addresses:
: FOR ${address} in @{addresslist}
\ log to console ${address}