Working with JSON

This week I wanted to talk a bit about JSON and how powerful it can be for developers. JSON played a big role in the creation of my very first plugin. Short for Javascript Object Notation, JSON has flexibility and a relative easy-to-learn format that can really help make working with complicated data structures easier for developers.

Typically you’ll see JSON used as the data format for sending back end data to a script on the front end and for responses from external APIs. In the case of my plugin, I wanted to display my “badges” that I earned from an online learning site. These badges, as well as pretty much every other piece of data tied to my account, are available in JSON format on this online learning site via their API. I can see data from every single course I have completed since I began using the site almost 2 years ago. I easily found the names of the courses, the dates I completed them, as well as the urls of both the courses themselves and the badge images tied to each course.

First I wrote a function to pull the JSON I needed from the site’s API:

function xxx_get_site_profile( $wp_username ) {

	// Set the API URL.
	$api_url = 'http://samplesite.com/' . $wp_username . '.json';

	// Set some args we'll pass to wp_remote_get().
	$args = array(
		'timeout' => 120,
	);

	// Get the response from the API.
	$api_response = wp_remote_get( $api_url, $args );

	$profile = json_decode( $api_response['body'] );

	return $profile;
}

This function simply returns the data from the API in JSON format. Notice how the $wp_username variable gets passed in so that any user’s info can be returned, if it exists. I’m also running the JSON through PHP’s json_decode() function before returning it, which will turn it into a standard PHP object that I can access just like any other object in PHP. This will come in handy throughout the process.

Here is a small sample piece of the raw JSON returned by the function:

{
  "name": "Jordan Gonzales",
  "profile_name": "jordangonzales",
  "profile_url": "https://samplesite.com/jordangonzales",
  "gravatar_url": "https://uploads.samplesite.com/production/profile-photos/608732/thumb_Picture_of_me_1.png",
  "gravatar_hash": "47344c7d11c55afbbe634c0bab4f43f0",
  "badges": [
    {
      "id": 49,
      "name": "Newbie",
      "url": "https://samplesite.com/jordangonzales",
      "icon_url": "https://achievement-images.samplesite.com/Generic_Newbie.png",
      "earned_date": "2014-03-22T02:09:36.000Z",
      "courses": [
         "title":"How to Make a Website",
         "url":"https://samplesite.com/library/how-to-make-a-website",
         "badge_count":1
      ]
    },
...

First, notice how “badges” is a nested array. All of the data related to badges is in this array. I can easily filter through the data and get only the pieces I want by interacting with the PHP object returned by my function above:

<ul class="wp-badges-frontend">

	<?php

		$wp_profile = xxx_get_site_profile( 'jordangonzales' );

		$total_badges = count( $wp_profile->badges );

		for( $i = $total_badges - 1; $i >= $total_badges - $num_badges; $i-- ):

	;?>

	...

Here I’m using count( $wp_profile->badges ) to get the number of total badges attached to my account. I want to display my most recent badges first and they are returned oldest first from the API, so I count the total number of badges and then use a for loop that decrements on each interation to build my output starting with the most recent badge. This loop could continue all the way down until my very first badge, or I can stop after a specific number.

<li class="wp-badge">

	<?php $badge = $wp_profile->badges[$i]; ?>

	<img src="<?php echo $badge->icon_url; ?>">

	<?php if ( '1' == $display_tooltip ) : ?>

	<div class="wp-badge-info">

		<p class="wp-badge-name">
			<a href="<?php echo $badge->url; ?>">

			<?php echo $badge->name; ?>

			</a>
		</p>

		<?php if ( $badge->
courses['title'] != '' ) : ?>

		<p class="wp-badge-project">

		<a href="<?php echo $badge->
courses['url']; ?>">

		<?php echo $badge->
courses['title']; ?>

		</a>

		</p>

		<?php endif; ?>

	</div>

	<?php endif; ?>

</li>


From here, we can begin isolating the individual pieces of data that we want to display. Notice that every piece of data we need must start at the highest level of the JSON tree, stored in the $wp_profile variable. We then use the “->” symbol to move one level down into “badges”. We continue to use this symbol down through the levels of arrays, getting more specific until we get what we need. The curly brackets hold the specific names of the data we are looking for , including “badges”, “name”, “courses”, “title”, “url”, and “icon_url”. See the text block above to look at this code in action. Now that we have our data, all we need to do is wrap it in html markup. Now we are free to style and arrange this data as needed.


Obviously there is still plenty of work left to do to get a fully functioning plugin. However, the flexibility and simplicity of using JSON moves things along tremendously. This was a simple example showing the potential power of JSON, and the possibilities are endless! Hopefully you found this piece informative, and that it inspires you to jump into JSON for your own development. Good luck!

Newsletter

Subscribe and stay connected through our Newsletter. We send out important news, tips and special offers.

  • This field is for validation purposes and should be left unchanged.