如何从量角器中的 JSON 对象中提取字符串

How to extract string from JSON object in protractor

我无法从 webstorm 的量角器中的 JSON 对象中提取字符串。我想要 statusCode 的值,即:200,下面提到的我为此尝试过的代码...

代码是:

console.log('body is :' + JSON.stringify(body));

var jsonResponse = JSON.stringify(response);

console.log('---------response is: '+ jsonResponse);

var statusResponse = jsonResponse.getString("statusCode");

console.log('---- statusResponse is :'+ statusResponse.toString());

输出是:

body is :{"oBody":{"payLoad":{"sLoginId":"HDB_TW_DSA@softcell.com","iInstId":4019,"sFirstName":"PRIYANKA","sLastName":"MADGUNDI","sEmail":"priyanka@softcell.com","sEmpId":"HDB18458","sMobile":"8237276692","bActive":true,"aRoles":["DSA"],"aDealers":[{"id":"TW423684019","iInstId":4019,"iDlrId":"42368","sDlrName":"GODSPEED MOTORCYCLE PVT LTD","iBranchId":1278,"sBranchName":"HYDERABAD-SF","sProduct":"TW","bActive":true},{"oStatus":{"iStatus":200,"sStatus":"OK"}}

---------响应是:

{"statusCode":200,"body":{"oBody":{"payLoad":{"sLoginId":"HDB_TW_DSA@softcell.com","iInstId":4019,"sFirstName":"PRIYANKA","sLastName":"MADGUNDI","sEmail":"priyanka@softcell.com","sEmpId":"HDB18458","sMobile":"8237276692","bActive":true,"aRoles":["DSA"],"aDealers","path":"/gonogo-api/atm/login-web-v3","href":"https://ssg.serviceurl.in/login-web-v3"},"method":"POST","headers":{"Postman-Token":"7aad048f-f8ad-4765-a0b8-be3b3a485ab6","cache-control":"no-cache","Content-Type":"application/json","accept":"application/json","content-length":380}}}

试试下面的选项

var res= JSON.parse(response);
console.log(res[0].statusCode);

希望对你有帮助

因此 jsonResponse 从字符串化中给你的内容似乎没有被 json 解析识别为完美的 json。所以你可以通过找到它说 "statusCode:" 的地方来自己进行解析,从 space 中获取响应字符串,只要 statusCode 可以是,然后是一些(8 个字符对我来说似乎足够),然后只考虑逗号。我假设你想要代码作为数字,而不是字符串,所以我转换了它。

var temp =jsonResponse.search('"statusCode":')+'"statusCode":'.length;
var temp2 = jsonResponse.slice(temp,temp+8);
var status = parseInt(temp2.slice(0,temp2.search(',')),10);