Fetching JSON

It's possible to fetch JSON from an external web address or API using the Z.getJSON(url, successFunc, errorFunc) function.

The getJSON function takes three parameters:

url : string
The web address to retrieve the data from.
successFunc : function
A function that will be called if the request is successful. This function will be passed the returned data as its only argument.
errorFunc : function
A function that will be called if the request fails or the data it returned wasn't valid JSON.

We highly recommend using HTTPS for all calls using this function. In addition to the security benefits for your users, Apple are deprecating HTTP-only network connections from apps.

Here's an example of using it to retrieve data about Zappar from a test JSON file we setup:

Z.getJSON("https://s3-eu-west-1.amazonaws.com/wizcontent/test/zappar.json", function(data) {
    if (data && data.company) {
        console.log("Zappar HQ is based in " + data.headOffice);
    } else {
        console.log("Unexpected response from API");
}, function() {
    console.log("Unable to retrieve information. Check your network connection.");

A request may fail for a number of reasons:

  • Lack of, or poor, network connection
  • The server wasn't accessible or didn't respond
  • The server responded with an error (e.g. 404, 500)
  • The data returned wasn't valid JSON

The getJSON function is a powerful way for making experiences dynamic or keeping them automatically up-to-date. Make sure to test your experience in a variety of network conditions to optimize the user experience - remember that the connections of mobile devices may be slow or missing.

More Information

zapcode branded_zapcode i