如何从具有JSON响应内容的变量中获取属性值

时间:2018-09-18 17:49:08

标签: json robotframework

我正在使用Robot Framework API自动化。在这里,将JSON响应存储在变量[POSTResp.content]中。即,“ POSTResp.content”具有完整的响应,如下所示。请帮助我从存储的内容中获取属性的值(例如,referenceId的值)。

JSON响应示例:

{
"serviceResponseHeader": {
    "responseContext": {
        "responseCode": "MS19",
        "responseDescription": "Success",
        "serviceResponseTimeInGMT": "18 Sep 2018 16:12:43 GMT"
    },
    "requesterContext": {
        "applicationCode": null,
        "applicationSubCode": null,
        "countryCode": null,
        "requesterReferenceNumber": null,
        "requestTimeInGMT": "30 Jun 2015 11:54:49 GMT",
        "requesterUserIdentity": "23483",
        "requesterGroupIdentity": "1620",
        "requesterIpAddress": "",
        "sessionIdentity": "2536kjhfdashfkhfsab",
        "ssoSessionIdentity": "2536kjhfdashfkhfsab",
        "requesterAbbreviatedGroupName": "NEWCOMP"
    },
    "serviceContext": {
        "serviceVersionNumber": "1.0",
        "serviceCode": "30"
    }
},
"getProxyDetailResponseBody": {
    "proxyDetails": {
        "proxyType": "",
        "proxyValue": "20140005K",
        "referenceId": "PR18090000847597",
        "transactionId": "18091801657466"
    }
}

}

我尝试了以下方法,

1)$ {json}到JSON $ {POSTResp.content}是 登录控制台\ n代理ID为$ {json [“ proxyValue”]}

结果:解析变量'$ {json [“ proxyValue”]}}'失败:TypeError:字符串索引必须是整数,而不是str

2)$ {json}评估json.loads($ {POSTResp.content}} json 登录控制台\ n代理ID为$ {json [“ proxyValue”]}

结果:失败:SyntaxError:解析(第1行)时出现意外的EOF

1 个答案:

答案 0 :(得分:1)

Issues with your two approaches:

1) the library keyword call passes a true argument (well, truth-like) to the pretty_print parameter:

 ${json}    To JSON    ${POSTResp.content}   true

Looking at the library's source, in that case the keyword does not return a dict object - but a string, a beatified version of the source json. That coincides with the error your received.
Remove the "true" argument and it must return a dict.

2) In the Evaluate surround the variable with triple quotes (python's literal string):

${json}    Evaluate    json.loads('''${POSTResp.content}'''} 

json

Without it, the framework just dumped the variable's value, which raised a python syntax error.

By the way, try not to make your variables with language keywords/library names - like ${json} up there.