Creating LoadRunner Script to capture Json Data - javascript

I am trying to create a loadrunner 'js' file to capture some data from a json. The json file is located on a web sever, this isn't the issue. I can successfully retrieve the json. However, I would like to return a particular value from the json text. I have attempted to do this on a local html page as follows, but I always get an error message:
Error is TypeError: Cannot read property 'Location' of undefined
Code:
<!doctype html> <head></head><script>
function getdata()
{
var jsontext = '{"Locations":{"Location":[{"#id":"3649","#latitude":"51.758","#longitude":"-1.576","#country":"England","#zoomLevel":"10","#obsZoomLevel":"5","#type":"Observing Site","#name":"Brize Norton","#geohash":"gcnyknk2h"},{"#id":"3","#latitude":"50.9503","#longitude":"-1.3567","#country":"England","#zoomLevel":"11","#type":"Airport and Heliport","#name":"Southampton Airport","#geohash":"gcp1c5hp4"}]}}';
var stringifiedjson = JSON.stringify(jsontext).replace(/#/g, '_'); //convert to JSON string
var data = JSON.parse(stringifiedjson);
json.innerHTML=data;
try{
var newlocation0 = data.Locations.Location[1]._id;
output.innerHTML=newlocation0;
return;
}
catch(err){
message.innerHTML = "(1)Error is " + err;
}
try{
var newlocation0 = data.Locations.Location[1]._id;
output.innerHTML=newlocation0;
return;
}
catch(err) {
message.innerHTML = message.innerHTML + "(2)Error is " + err;
}
try{
var newlocation0 = data.Locations.Location[0]._id;
output.innerHTML=newlocation0;
return;
}
catch(err) {
message.innerHTML = message.innerHTML + "(3)Error is " + err;
}
}
</script>
<body>
Error Messages:
<p id="message"></p>
<BR><BR>
JSON Input:
<p id="json"></p>
<BR><BR>
Output:
<p id="output"></p>
<button onclick="getdata()">Check</button>
<button onclick="location.reload();">Reload</button>
</body>
I have tried different combinations of notations of [0] and [1] but I cannot get an output for the right part of the json.

jsontext is initially a string
var jsontext = '{"Locations":{"Location":[{"#id":"3649","#latitude":"51.758","#longitude":"-1.576","#country":"England","#zoomLevel":"10","#obsZoomLevel":"5","#type":"Observing Site","#name":"Brize Norton","#geohash":"gcnyknk2h"},{"#id":"3","#latitude":"50.9503","#longitude":"-1.3567","#country":"England","#zoomLevel":"11","#type":"Airport and Heliport","#name":"Southampton Airport","#geohash":"gcp1c5hp4"}]}}';
you have wrapped that string in another string
var stringifiedjson = JSON.stringify(jsontext).replace(/#/g, '_');
the resulting string looks like this
""{\"Locations\":{\"Location\":[{\"_id\":\"3649\",\"_latitude\":\"51.758\",\"_longitude\":\"-1.576\",\"_country\":\"England\",\"_zoomLevel\":\"10\",\"_obsZoomLevel\":\"5\",\"_type\":\"Observing Site\",\"_name\":\"Brize Norton\",\"_geohash\":\"gcnyknk2h\"},{\"_id\":\"3\",\"_latitude\":\"50.9503\",\"_longitude\":\"-1.3567\",\"_country\":\"England\",\"_zoomLevel\":\"11\",\"_type\":\"Airport and Heliport\",\"_name\":\"Southampton Airport\",\"_geohash\":\"gcp1c5hp4\"}]}}""
parsing once returns the inner JSON string
var data = JSON.parse(stringifiedjson);
to get the object from string parse again
data = JSON.parse(data);
OR
there is no need for JSON.stringify in the first place, you can just use the replace method.

Related

How to get JavaScript output as string in CefSharp?

I am trying to get the output of this javascript string but so far what I have tried did not work
My current code is this. response is blank what I want is 4
var task = chromiumWebBrowser1.EvaluateScriptAsync("2+2");
var response = task.Result;
MessageBox.Show(String.Format("output", response));
Any help would be great.
The EvaluateScriptAsync method returns Task<JavascriptResponse>. You can await the Task to obtain the JavascriptResponse object then get the Result or error.
JavascriptResponse response = await chromiumWebBrowser.EvaluateScriptAsync("1 + 1");
if (response.Success)
{
var onePlusOne = (int)response.Result;
}
else
{
var error = response.Message;
}

Setting setRequestBody for Rest web services using Post method

Hi I'm trying to create a rest response using post method, I want to dynamically pass the variables instead of hard coding,But where i fail is,when I'm trying to to send an array as a parameter to the Rest web service using post method(example array ["CN=XXX_XX,OU=XXXXX,OU=1_XXXX XXXXity Groups,DC=XXXX,DC=local"]) and I know that there is a better way to do that Please find my code sample.This is the method that gives me a appropriate result.
First Method:(Works)
`
try {
var r = new sn_ws.RESTMessageV2('SailPoint_IdM', 'post');
var txt = "{\r\n\t\"workflowArgs\":\r\n\t{\r\n\t\"identityName\":\"SiamR\",\r\n\t\"appName\":\"Active Directory\",\r\n\t\"listEntitlements\":[\"CN=ER_CxxxK,OU=xxxxx,OU=1_xxxxxx Security xxx,DC=xxxx,DC=local\"],\r\n\t\"operation\":\"Add\",\r\n\t\"ticketNumber\":\"RITM1234567\"\r\n\t}\r\n}";
r.setRequestBody(txt);
var response = r.execute();
var ResponseBody = response.getBody();
var HTTPCode = response.getStatusCode();
gs.log(ResponseBody);
gs.log(HTTPCode);
} catch (ex) {
var message = ex.getMessage();
}
output:
Script: {"attributes":{"requestResult":{"status":"Success"}},"complete":false,"errors":null,"failure":false,"metaData":null,"requestID":"2c988d8c5bd47cf7015bebfb64cf01e6","retry":false,"retryWait":0,"status":null,"success":false,"warnings":null}
Script: 200
2n Method (Does not Work):
try {
var r = new sn_ws.RESTMessageV2('SailPoint_IdM', 'post');
r.setStringParameter('"listEntitlements"', '["CN=Exxx_xxxK,OU=xxxxion,OU=1_xxxxx Security xxxx,DC=xxx,DC=xxxx"]');
r.setStringParameter('"identityName"', '"SiarmR"');
r.setStringParameter('"appName"', '"Active Directory"');
r.setStringParameter('"ticketNumber"', '"RITM1234567"');
r.setStringParameter('operation', '"Add"');
//override authentication profile
//authentication type ='basic'/ 'oauth2'
//r.setAuthentication(authentication type, profile name);
var response = r.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();
gs.log(responseBody );
}
catch(ex) {
var message = ex.getMessage();
}
output:
Script: {"attributes":{"requestResult":{"errors":["An unexpected error occurred: sailpoint.tools.GeneralException: The application script threw an exception: java.lang.NullPointerException: Null Pointer in Method Invocation BSF info: script at line: 0 column: columnNo"],"status":"FAIL","GroupStatus":null,"AppStatus":null}},"complete":false,"errors":["Status : failed\nAn unexpected error occurred: sailpoint.tools.GeneralException: The application script threw an exception: java.lang.NullPointerException: Null Pointer in Method Invocation BSF info: script at line: 0 column: columnNo\n"],"failure":false,"metaData":null,"requestID":null,"retry":false,"retryWait":0,"status":null,"success":false,"warnings":null}
Script: 200
Im facing issue with this parameter as im trying to pass this as aray paramenter '["CN=Exxx_xxxK,OU=xxxxion,OU=1_xxxxx Security xxxx,DC=xxx,DC=xxxx"]'
Please suggest a way to implement this and to pass all the variables dynamically if suggesting first method
Below is one of my function, to handle dynamic parameters in either appear in request endpoint (url), headers or body;
For eg: parameter p
var p = {abc: 'def'};
and outbuond rest settings:
rest url = https://xxxx.sss.com/api/showme?name=${abc}
rest headers name = custom-header; value = ${abc}
rest body = {name: "${abc}"}
so it will replace all ${abc} to 'def'
_.isNullOrEmpty - check is obj, string or array is null or empty;
_.loop - loop an obj or array, pass in function(nm/i, val) {}
_.isArray - to check if is array
_.str - convert anything to string
_.rpl - replace all string A to B
restParameters: function (restRequest, obj, endpoint) {
var _ = this;
if ((_.isNullOrEmpty(restRequest)) || (_.isNullOrEmpty(obj))) return;
if (_.isNullOrEmpty(endpoint)) endpoint = restRequest.getEndpoint();
var body = restRequest.getRequestBody();
var headers = restRequest.getRequestHeaders();
_.loop(obj, function(nm, val) {
if (_.isArray(val)) {
val = (_.isNullOrEmpty(val)) ? '[]' : JSON.stringify(val);
} else val = _.str(val);
//for my case my array pass in as string become: "[\"1\", \"2\"]"
//comment below if pass in as object
if (val.contains('"')) val = _.rpl(val, '"', '\\"');
restRequest.setStringParameterNoEscape(nm, val);
var sch = '${' + nm + '}';
endpoint = _.rpl(endpoint, sch, val);
body = _.rpl(body, sch, val);
_.loop(headers, function (hn, hv) {
headers[hn] = _.rpl(hv, sch, val);
});
}, true);
restRequest.setEndpoint(endpoint);
restRequest.setRequestBody(body);
_.loop(headers, function (hn, hv) { restRequest.setRequestHeader(hn, hv); });
}

Remove characters from variable with Javascript

My variable looks as following:
response = "{ tradeofferid: '63341523' }"
I would like to remove all characters except for the letters and the semicolon.
I tried using the replace function but I get some errors.
function(err, response) {
if (err) {
throw err;
}
var result = response;
result = result.replace(/[{}]/g, "");
console.log(offerStatus);
res.end(result);
});
My console points at replace and the error log says: undefined is not a function
What I want to end up with is
response = "tradeofferid: 63341523"
response = { tradeofferid: '63341523' };
alert(response.tradeofferid);
for(var name in response) {
alert(name);
var value = response[name];
alert(value);
}
responseString = name + " : " + value;
alert(responseString);
You may try this but this answer is only specific to your question. This will not work if you have more than one attributes in "response" object.
response = "tradeofferid: " + JSON.parse(response)[tradeofferid]
... if you really want a string for display or something, but I'm guessing you actually just want to parse the JSON and pass the object around but haven't realized it yet.
You need to set something to be replaced in the .replace method. Try with:
var result = response.replace(/[^A-Za-z0-9\: ]/g, "")

JSON .concat() function in google app script

I have tried to concatenate two JSON objects in Google App Script however it always gives me the following error:
TypeError: Funktion concat in Objekt [object Object] nicht gefunden (Zeile 53, Datei "")
What are the solutions for this problem? I guess the concat() function is not part of the Google App Script API.
What I am trying to do:
Read Schema.org JSON from various E-Mails and try to save this data in a .json file.
Code:
function extractFromGmail(subject,jsonName) {
subject = "json";
jsonName = "testjson";
var rawData = "";
var threads = GmailApp.search('subject:' + subject);
Logger.log("thread length: " + threads.length);
var json;
for(var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
var message = messages[0];
rawData += message.getRawContent();
// Logger.log("rawData from e-mail: " + rawData);
if(rawData.search('itemscope') > -1) {
if(json === null) json = this.extractMicrodata(rawData, jsonName);
else json.concat(this.extractMicrodata(rawData, jsonName));
}
if(rawData.search("json") > -1) {
if(json === undefined) {
Logger.log("undef");
json = this.extractJSON(rawData, jsonName);
}
else {
json = JSON.stringify(json);
Logger.log(typeof json);
json = JSON.parse(json);
Logger.log(typeof json); //this part is to test that it's a json-obj
var result = this.extractJSON(rawData, jsonName)
json = json.concat(result);
}
}
Logger.log(JSON.stringify(json));
}
There is no Object.concat() method. My guess is what you really want is to create an array, and then use .push() to add objects to that array, and then stringify the entire array at once.
But your question is phrased too vaguely to be certain that's what you need.

string.replace not working in node.js express server

I need to read a file and replace some texts in that file with dynamic content.when i tried string.replace it is not working for the data that i read from the file.But for the string it is working.I am using node.js and express.
fs.readFile('test.html', function read(err, data) {
if (err) {
console.log(err);
}
else {
var msg = data.toString();
msg.replace("%name%", "myname");
msg.replace(/%email%/gi, 'example#gmail.com');
temp = "Hello %NAME%, would you like some %DRINK%?";
temp = temp.replace(/%NAME%/gi,"Myname");
temp = temp.replace("%DRINK%","tea");
console.log("temp: "+temp);
console.log("msg: "+msg);
}
});
Output:
temp: Hello Myname, would you like some tea?
msg: Hello %NAME%, would you like some %DRINK%?
msg = msg.replace(/%name%/gi, "myname");
You're passing a string instead of a regex to the first replace, and it doesn't match because the case is different. Even if it did match, you're not reassigning this modified value to msg. This is strange, because you're doing everything correctly for tmp.
You need to assign variable for .replace() which returns the string. In your case, you need to do like, msg = msg.replace("%name%", "myname");
Code:
fs.readFile('test.html', function read(err, data) {
if (err) {
console.log(err);
}
else {
var msg = data.toString();
msg = msg.replace("%name%", "myname");
msg = msg.replace(/%email%/gi, 'example#gmail.com');
temp = "Hello %NAME%, would you like some %DRINK%?";
temp = temp.replace(/%NAME%/gi,"Myname");
temp = temp.replace("%DRINK%","tea");
console.log("temp: "+temp);
console.log("msg: "+msg);
}
});
replace() returns a new string with the replaced substrings, so you must assign that to a variable in order to access it. It does not mutate the original string.
You would want to write the transformed string back to your file.

Categories

Resources