Read and use JSON data in a template
The
Liquid Template Language has a built-in filter to parse JSON called parse_json
.
If your theme uses Radius, see "Radius" below.
This tutorial assumes that you already have a JSON endpoint available to consume. For the purposes of this tutorial, we're going to use the Faker API and their Persons JSON endpoint:
- First, get the URL for your JSON endpoint, eg:
https://fakerapi.it/api/v1/persons?_quantity=10
. - Next, choose a template to make edits to. We'll go with
backpage.html
. - In
backpage.html
, paste the following code:
{% assign directory = 'YOUR_JSON_ENDPOINT_URL_HERE' | web_request | parse_json %}
<ul>
{% for person in directory.data %}
<li id="directory-id--{{ person.id }}" style="margin-bottom: 4rem;">
<p>{{ person.firstname }} {{ person.lastname }}</p>
<p>{{ person.phone }}</p>
<p><a href="mailto:{{ person.email }}">{{ person.email }}</a></p>
<img src="{{ person.image }}" alt="{{ person.firstname }} {{ person.lastname }} profile">
</li>
{% endfor %}
</ul>
- We're going to use the Faker API, so let's replace
YOUR_JSON_ENDPOINT_URL_HERE
withhttps://fakerapi.it/api/v1/persons?_quantity=10
. That should look like this:
{% assign directory = 'https://fakerapi.it/api/v1/persons?_quantity=10' | web_request | parse_json %}
- If you have followed these instructions, you should now see the template output data from this JSON after pushing to production. Congrats!
NOTE: If you use a different JSON endpoint, you'll have to modify the
dot notation to suit your data. To see what the data object looks like in CleanSlate,
you can output it by pasting {{ directory }}
anywhere into the template.
To see a single record, you could do something like {{ directory.data[0].firstname }}
.
Again, modify the dot notaion to suit your endpoint.
Radius
Unfortunately, the Radius Template Language does not have a way to natively parse JSON. If you want to use JSON in a theme that uses Radius, use JavaScript to render the data from JSON on page load.
Not sure what that means? Follow this tutorial on YouTube (or any number of others) for more information.
Last updated on November 9, 2022.
We welcome all questions, feedback and bug reports. If you're having an issue, we usually need the following information:
- A brief description of the issue
- A link to the page where you saw the issue
- Screenshots that illustrate the problem - How do I take a screenshot?
Kindly email CleanSlate@mail.wvu.edu for help or use the form on the request help page.