Parsing JSON data in Javascript
I'm trying to sort out how to parse the JSON data from a GET request using an API. The goal is to take the individual fields and save them to Project level variables to use in Property Checkpoints. The code below is the example function from aqHttpResponse Object | TestComplete Documentation (smartbear.com). The thought is that I should be able to use the line in orange down below, as well as other lines of code, to set the individual fields of the response to variables. I probably have the wrong syntax as I'm not super familiar with Javascript. Is it possible to take the data directly from a GET request and set it to a variable, does the data need to be parsed first, or is this not possible at all in TestComplete?
function httpGetRequest()
{
var address = "http://httpbin.org";
// Create an aqHttpRequest object
var aqHttpRequest = aqHttp.CreateGetRequest(address);
// Send the request, get an aqHttpResponse object
var aqHttpResponse = aqHttpRequest.Send();
if (aqHttpResponse != null)
{
// Read the response data
Log.Message(aqHttpResponse.AllHeaders); // All headers
Log.Message(aqHttpResponse.GetHeader("Content-Type")); // A specific header
Log.Message(aqHttpResponse.StatusCode); // A status code
Log.Message(aqHttpResponse.StatusText); // A status text
Log.Message(aqHttpResponse.Text); // A response body
// This is the test line, likely the wrong syntax
Project.Variables.Name = aqHttpResponse.Text.Name;
// Save the response body to a file and place it to the project folder
aqHttpResponse.SaveToFile(Project.Path + "body.txt");
}
}
Hi,
It's a bit difficult drilling into this now as I'm UK-based. I can try and look on Monday, but in the meantime, try building the path incrementally....
Log.Message(aqHttpResponse); Log.Message(aqHttpResponse.Text); Log.Message(aqHttpResponse.Text.search_player_all); Log.Message(aqHttpResponse.Text.search_player_all.queryResults);
I also wonder whether the response has come back as a string and firstly needs to be cast to a JSON Object. Thinking about it, that is likely.
From W3 (https://www.w3schools.com/js/js_json_parse.asp)....
const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); console.log(obj.name);
You could try....
const myObj = JSON.parse(aqHttpResponse.Text); // Cast a string to JSON Object. Log.message(myObj.Text) // If you get a response here, we're winning. // Then try and navgigate through your object.