The previous blog talked about how to create an API query to enable us to programmatically access these APIs. Before we go into UI for the data, it is useful to understand the data that these APIs return.
Most APIs return data in one or both of the two formats – JSON and XML. They are textual data formats with well-defined ways to represent data which is both human and machine readable. The data formats themselves do not define the structure of the data. Thus, they are flexible and general enough to be used by any API service provider to represent their data.
JSON is a collection of name-value pairs, where a value can be of the type number, string, boolean, array or another object. A simple example of JSON data is:
The JSON object phonebook is an array comprising of 2 objects. Each of these objects has two poperties – name and phone – associated with their corresponding values.
JSON.parse allows you to convert the JSON string to an object. Accessing any specific element would then be equivalent to traversing the JSON object. For example, in order to access the name of the first person in the phone book:
var json = JSON.parse(jsonString);
var nameOfFirstPerson = json.phonebook.name;
XML or Extensible Markup Language, as the name suggests, is a markup language which was designed to transport data between server and client. While the use of XML has come down recently, it is still a prevalant data format supported by several APIs, especially legacy ones.
XML looks very much like HTML, with tags and text content associated with each tags. You can define your own tags, allowing it to be used as a generalized format to represent API data. A simple example of XML data is:
<name> ABC </name>
<name> XYZ </name>
In the above data, “person”, “name”, “phone” are all XML tags. Since XML is similar to a DOM element, we can use the DOM parser that is available on most modern browsers to parse the XML string. This is done by:
var parser = new DOMParser();
var xml = parser.parseFromString(xmlString, “text/xml”);
This function returns the associated xml object. You can then query for child nodes and child elements using the same functions that work on any DOM element.
App Framework library makes this easy by abstracting out all the murky details into its $ functionality. $(xmlString) converts the string into an xml element. Accessing the rest of the elements is similar to traversing a DOM tree using functions such as find, childNodes, text etc..
var xml = $(xmlString);
var nameOfFirstPerson = xml.find("name").text();
More detailed documentation of the query selector functions can be found at App Framework library’s documentation site.