Parsing JSON format responseText - not as easy/clearcut as XML. Does it even work?
The usefulness of JSON is clear in that you can you use key-value pair 'get()' method to retrieve the value of a key...which in theory is a lot easier than used Xpath and XML...but I have found this to be difficult to resolve when using getURL or postURL and I need to parse the responseText that gets sent back.
In the case of the example I have dealt with the JSON format data, I think it is sending back a multi-dimensional array of data...and my assumptions about using get(keyname) seem to break down.
The code below illustrates...I get a null value when I try to get the string from a call to get("application-name") which is definitely the first key...my intention was to then convert the returned string, to another map variable and bit by bit get to the text I wanted. But as I said...it fails at the first hurdle.
If anyone know, please advise on how one should parse JSON format data return by postURL and/or getURL....
Code is below...
- ResponseMapVariable = postUrl("http://creator.zoho.com/api/json/apitite/forms/apikey=" + theAPIKey + "&ticket=" + theTicket, mapvariable,false);
- ResponseCode = ResponseMapVariable.get("responseCode");
- ResponseText = ResponseMapVariable.get("responseText");
- thisapp.globalvars.SetWidelyUsedTestVariable("Post URL JSON Tests - ResponseCode and ResponseText are : " + ResponseCode + " " + ResponseText);
- //
- // Using XML to decode the response data works fine...
- // This code was got from here - http://help.creator.zoho.com/Get-Data-From-External-Website.html
- //
- info "These are the XML parsing results....";
- xmldata = ResponseText.toXML();
- strdata = xmldata.executeXPath("/root/application-name/formList");
- xmllist = strdata.toXmlList();
- info "Number of Apps is : " + xmldata.executeXPath("/root/application-name/formList/formCount/text()");
- for each r in xmllist
- {
- info "App name : " + r.executeXPath("/formList/componentname/text()");
- info "Display name : " + r.executeXPath("formList/displayname/text()");
- info "Link ID : " + r.executeXPath("/formList/linkid/text()");
- }
- // ALAS MAP AND JSON DIDN'T GET ON AS WELL AS I HAD HOPED....get("application-name") is not working as expected...
- // I THINK THIS IS BECAUSE IT'S A MULTI-DIMENSIONAL ENTITY - IF IT WAS A FLAT KEY-VALUE PAIR ARRAY, I THINK IT WOULD WORK...
- // Convert the Text to a more useful map...it is naturally in JSON format
- info "These are the JSON parsing results....";
- mapFromResponseText = ResponseText.toMap();
- info "mapFromResponseText is " + mapFromResponseText;
- // This line FAILS...a null is returned..
- theKeyValue = mapFromResponseText.get("application-name");