How to extract string from JSON object in protractor - json

I am not able to extract string from JSON object in protractor in webstorm. I want value of statusCode i.e :200, The code I've tried for this mentioned below...
CODE IS :
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());
OUTPUT IS:
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"}}
---------response is:
{"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}}}

Try the below option
var res= JSON.parse(response);
console.log(res[0].statusCode);
Hope it helps you

So it appears what jsonResponse is giving you from the stringifying is not recognized as perfect json by json parse. So you can do the parsing yourself by finding where it says "statusCode:", taking the response string from a space beyond that for as long as statusCode could be and then some (8 characters seemed plenty to me), then taking only up to the comma. I assumed you want the code as a number, not a string, so I converted it.
var temp =jsonResponse.search('"statusCode":')+'"statusCode":'.length;
var temp2 = jsonResponse.slice(temp,temp+8);
var status = parseInt(temp2.slice(0,temp2.search(',')),10);

Related

GetCapabilities Query for TileServer Returns Malformed JSON

I have installed TileServer.php. When I navigate to it, I can see my tiles (so it's working).
My issue is when I query for the getCapabilities file the resulting json file is malformed.
The json is prefixed with part of the query string at the start of the json response.
Here is the full query string:
http://<=my ip=>/tileserver/index.html?service=wmts&request=getcapabilities&version=1.0.0
Actual Json Response I Receive
(Notice wmts&request is prefixed to the otherwise valid json)
====JSON===============================
wmts&request([{"name":"190322","type":"overlay","description":"190322","version":"1.1","format":"png","bounds":[174.92249449474565,-36.991878207885335,174.93635413927785,-36.98244705946717],"maxzoom":22,"minzoom":14,"basename":"1313_190322","profile":"mercator","scale":1,"tiles": ...
==================================================
I have tried removing part of the query string to test for the results, oddly enough it grabs the part of the query string again.
Here is the full query string I tested with:
http://<=my ip=>/tileserver/index.html?request=getcapabilities&version=1.0.0
(Actual Json Response I Receive)
====JSON===============================
getcapabilities&version([{"name":"190322","type":"overlay","description":"190322","version":"1.1","format":"png","bounds":[174.92249449474565,-36.991878207885335,174.93635413927785,-36.98244705946717],"maxzoom":22,"minzoom":14,"basename":"1313_190322","profile":"mercator","scale":1,"tiles": ...
=======================================================
I could parse this out I suppose but I would like to find the cause for this issue.
I am using ASP.Net 5.0.
Here is roughly my code:
private static readonly string _tileserver_ip = "http://<my ip>/tileserver/";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var query = new Dictionary<string, string>
{
["service"] = "wmts",
["request"] = "getcapabilities",
["version"] = "1.0.0"
};
var response = await client.GetAsync(QueryHelpers.AddQueryString(_tileserver_ip, query));
var capabilitiesString = await response.Content.ReadAsStringAsync();
// the result of the query string => "http://<my ip>/tileserver/?service=wmts&request=getcapabilities&version=1.0.0"
EDIT
Opps! Turns out I was requesting the getCapabilities file from the TileServer in the completely wrong way.
I will leave this here encase it helps someone in the future.
Here is the correct URL: http://<= my url =>/tileserver/1.0.0/WMTSCapabilities.xml/wmts
I found the answer and I will leave this post here encase it helps someone in the future.
In my URL I was using index.html as the index page, however I should have been using index .json instead.
As soon as I switched to .json I received the JSON response as I was expecting.
Full URL with query string:
http://<=my ip=>/tileserver/index.json?service=wmts&request=getcapabilities&version=1.0.0

How do I get the session ID from an HTML response in postman

I am trying to get the sess_id from the html response in postman.
this is my test.
var test3 = cheerio(pm.response.text());
var variabile = test3.find('[pageId="/Security/SelectPaymentMethod?sess_id=SbyYFpsCefH3hVD3KNB7JwJ7VsYxdNBA1PKDbDJugmNZZyNZIJZeVdAb9H1neJfarNelwg6qXZx&paymentMethodCode=VEC&paymentMethodTypeCode=QTA&environment=Test"]').val();
console.log(variabile('sess_id').val());
HTML
<link accesskey="1" pageId="/Security/SelectPaymentMethod?sess_id=HnapitQl8k9CBhiCkeaKPQP681rb8kFkHmgZKYRbxNw9SxMMcUtwpsKn5bA2s2drwwBzv3S3W1T&paymentMethodCode=VEC&paymentMethodTypeCode=QTA&environment=Test">Verve eCash - Active</link>
in my console I get the response
TypeError | variable is not a function
This is a different and horrible way you could get that value:
let resData = xml2Json(pm.response.text());
let filteredData = resData.link.$.pageId.split('=')
console.log(filteredData[1].split('&')[0])
It's using xml2Json and passing that the response as text, it's then traversing down the data and splitting the pageId value. Not clean at all and I wouldn't use this anywhere other than figuring out a better solution but it's proving it can be done.
Thanks Danny for the effort.
Though I figured out another way.
I converted the xml to JSON first of all and made the test in JSON
let resp = xml2Json (pm.response.text()),
ussdsessionId = resp.page.navigation.link['2'].$.pageId;
console.log({ ussdsessionId });
pm.environment.set("sessionBank", ussdsessionId);

Webapi return json with extra double slashes for a path property

I am using asp.net webapi and returning json response. One of the property in the json response has got a path field. When i check in Console.WriteLine i get the values without additional double slashes. But the json response in postman contains extra double slashes.
Expected:
\\test.com\cax\mef\160704\160704Z003.abc
But in the json response the output i am getting is:
"path": "\\\\test.com\\cax\\mef\\160704\\160704Z004.abc"
And my json settings in webapi.config:
var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Can anyone help me what is the problem and how to solve this?
Why i am getting extra double slashes?
Thanks
The added slashes are their as Escape characters.
This Could be caused when you asign the URL to the Variable before you return the response via the Webapi. Eg:
xObj.path = urlPath;
----------------
xObj.path = urlPath.ToString();
It All Depends on where and how you Assigned them.. If they are coming for a Database they could have also Been Stored Like that.
it could also just be the IDE showing it to you Like that. This Often Just Adds the Escape characters to the interpretation of the value.. but when the value is used they are no longer present.
this is how you parse the JSON
var jsonResponse = '{ "firstName":"John" , "lastName":"Doe", "path" : "/test/test/adasdasd.com" }';
var obj = JSON.parse(jsonResponse);
console.log(obj);
You Will note that my Example doesn't have the double slashes. That is because if you use the response directly it wont have any either.

JSON String parsing each character as an object

I have a JSON file that contains what I believe to be a correct JSON string:
{"title": "exampleTitle", "tipTitle": "exampleTipTitle", "tip": "exampleTip"}
I'm trying to parse said file and take out the 3 values then store them in variables, however currently, it parses each individual character as a separate object, therefore:
JSONobj[1] = "
and so on. Assuming that currentLocation = the directory location of the json file.
Code
var jsonLocation = currentLocation + "json.txt";
var request = new XMLHttpRequest();
request.open("GET", jsonLocation, false);
request.send(null);
var returnValue = request.responseText;
var JSONobj = JSON.parse(JSON.stringify(returnValue));
var headerTitle = JSONobj[0];
A few clarifications, the stringify is in because it was throwing an unexpected token error. I've tried changing the file tile to .json instead but that also makes no difference. "It also gives off a XMLHttpRequest on the main thread is deprecated" but I'm not particularly sure how to solve that issue. Any help would be appreciated.
var returnValue = request.responseText;
Here returnValue is a string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
var JSONobj = JSON.parse(JSON.stringify(returnValue));
Here you convert the string of JSON to JSON. So you have a JSON string representing a string, and that string is a representation of a data structure in JSON.
"\"{\\"title\\": \\"exampleTitle\\", \\"tipTitle\\": \\"exampleTipTitle\\", \\"tip\\": \\"exampleTip\\"}"
Then you parse it and convert it back to the original string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
So you end up back where you start.
Just don't use JSON.stringify here, and you'll convert your JSON to a JavaScript object:
var javascript_object = JSON.parse(returnValue);
Then you have an object, but it doesn't have a 0 property so it doesn't make sense to access it with javascript_object[0]. The properties have names, such as javascript_object.title.
Your JSON doesn't describe an array, so indexing into it with an index like 0 doesn't make sense. Your JSON describes an object, which will have properties with the names title, tipTitle, and tip.
Additionally, you're overdoing your parsing: You just want to parse, not stringify (which is the opposite of parsing):
var JSONobj = JSON.parse(returnValue);
So:
var JSONobj = JSON.parse(returnValue);
var headerTitle = JSONobj.title;
console.log(headerTitle); // "exampleTitle"
Side note: By the time you've assigned it to the variable you've called JSONobj, it isn't JSON anymore, it's just a normal JavaScript object, so that name is a bit misleading. If you're writing source code, and you're not dealing with a string, you're not dealing with JSON anymore. :-)

Parse json string that carries a collection of objects in actionscript using Json.parse

I am running into an error parsing a json string with JSON.parse(...)
var str:String= '[{"AA":"A1", "BB":"32"}, {"AA":"A2", "BB":"12"}, {"AA":"A3", "BB":"14"}]';
var propertySets:Object = JSON.parse(str);
I can tell that I am getting the syntax wrong with constructing the JSON string but I have tried quite a few things before giving up. Any help with how to deal with collections would be great.
The following simple case works for me
var str:String= '{"test":"line1"}';
var propertySets:Object = JSON.parse(str);
Thank you
The syntax in the JSON string is correct. The way it is formatted will return an Array instance from JSON.parse(). The following code works for me:
var str:String = '[{"AA":"A1", "BB":"32"}, {"AA":"A2", "BB":"12"}, {"AA":"A3", "BB":"14"}]';
var propertySets:Array = JSON.parse(str) as Array;
trace(propertySets[0].AA); // prints "A1"
trace(propertySets[0].BB); // prints "32"
Shot in the dark since I don't know actionscript, but try wrapping the array in an object
var str:String= '{"objectArray":[{"AA":"A1", "BB":"32"}, {"AA":"A2", "BB":"12"}, {"AA":"A3","BB":"14"}]}';