Working with JSON and APIs with Processing

Oct 2014

After inevitably straying away from traditional Web Development with my uni course this year, i’ve ended up diving into Processing, a Java-based ‘language’ a bloody fantastic tool for painless data visualisation. This weekend I had a shot at integrating JSON and APIs with Processing.

I set out to create a super-simple program that will pull in the current weather condition of Goldsmiths (where I’m currently studying) and display this with a corresponding image. Being new to working with JSON and APIs, I went for something that was relatively straight forward, open and accessible: This saved me having to deal with any OAuth or authentication.

Processing thankfully has an innate json library which offers methods and objects to hold store and deal with json data. There’s also a HTTP request library for Processing.

Using Processing’s JSONObject

So long as you have the path to the JSON file, you can store the JSON data in a JSONObject in Processing (Note: You can use both absolute paths for HTTP requests and relative paths for local JSON files):

// Initialises a new JSONObject, initialJson, with the JSON file from located at x
JSONObject initialJson = loadJSONObject("x");

This will now store the JSON file at x location in a new JSONObject named initialJSON. This can now be accessed and targeted to manipulate specific information in the JSONObject.

Breaking down the JSON object

Below, I am creating a new JSONArray, weatherArray, and getting the “weather” array from the initialJson JSONObject.

// Creates a new JSONArray, weatherArray, where I will store the "weather" array from the initialJson object.
JSONArray weatherArray = initialJson.getJSONArray("weather");

I can then find the value pair/string in that JSONArray that corresponds to the key that I would like. In my example, I am needing the “main” key which contains a string value of the current weather condition.

// Declares a string, weatherState which gets the string value stating the weather condition. 
String weatherState = weatherObject.getString("main");

(Obviously these methods above are specific to the JSON file I am using in my demo!)

And bam, you have the desired weather value stored in a string, that updates real-time from the JSON file stored at the URL above. You’re ready to cause all sorts of carnage with this real-time string value. You can then go on to map this into some kinda crazy visualisation. There is a huge scope of opportunity to use a whole range of APIs, Twitter, Facebook, Instagram etc. Integrating this with Processing means that you can create visualisations of the data from these APIs which is a super exciting prospect. I’ll probably start working on using some bigger APIs soon.