JSON

by Justin Stayton | Last edited: 1/22/2020

Since its inception, getContent has output one thing: HTML. This has worked well considering that getContent is executed in the context of a website where HTML is the native language. As the complexity of websites has increased over the years, however, it's become common to use the noecho parameter with PHP's explode function to facilitate a makeshift JSON-esque type of output. Well, no longer! As of October 2016, we're excited to support a second type of output: JSON in the form of an associative array.

How it works

Using this new output type couldn't be easier. Simply pass the parameter json to the getContent call. Here's a complete example, which we'll dissect below:

<?php
$sermons = getContent(
  'sermon',
  'display:list',
  'json'
);
?>

<? foreach ($sermons['show'] as $sermon): ?>
  <h1><?= $sermon['title'] ?></h1>
<? endforeach; ?>

You'll notice a few things:

  1. There's no need to include the noecho parameter, as it's assumed and doesn't need to be passed explicitly.
  2. There's no need to include show, before_show, after_show, etc. as parameters to the getContent call. Instead, these are the top-level keys in the associative array that's returned.
  3. If multiple records are expected (such as the above call to list), the top-level keys (like show) will be an array of arrays that contain the tag values for each record; if only one record is expected, they will be an array with the tag values.
  4. Tags like __title__ are now title without the underscores.

Besides that, you can continue to use all of the same tags, grouping, sorting, and limiting that you've become accustomed to with getContent.

Tag parameters

There is one case where show, before_show, after_show, etc. make their return: when specifying tag parameters. It's done the same way as always:

$content = getContent(
  'sermon',
  'display:list',
  "show:__preview limit='100'__",
  "show:__date format='j/m/Y'__",
  'json'
);

In many cases (such as this one), tag parameters are unnecessary with the increased flexibility of the JSON output and use of standard PHP functionality. For example, preview could easily be limited to 100 characters with:

<?= substr($content['show']['preview'], 0, 100) ?>

We recommend this route over tag parameters when possible.

Unsupported display types & modules

There are a number of module display types that return HTML without the use of any tags for show, before_show, after_show, etc. One example is navigation:breadcrumbs, which returns a string of links denoting the ancestry of a specified page. In these cases, JSON output is not supported, and getContent will return 0 to signify an error occurred.

None of the ecommerce modules support JSON output either.