Using JSON Data in templates
I love JSON. It’s a simple data exchange format that’s extendable, simple to write, and really, really easy to parse when you’re in an HTML/CSS/Javascript environment. I generally use it to transfer small bits of data between PlanetPress Workflow and Connect Designer through the DataMapper using a singe local variable (see the tip on doing that on this page).
So let’s say you have a JSON string that looks like: {"authenticated": true, "username": "Evie", "sessionid": "2345LKTJ345HOIJEW450"}
, and this indicates to your template that a user is logged in and to show the “logout” button, the username, etc. This is set to the user_data variable in Workflow, passed on through datamapper into the data model used in the Designer module, with the field name user_data.
To use this data you’ll need a script. Let’s say I want to extract the username. The script would look like this (say, on a #username selector for the div with that ID):
var user_data = JSON.parse(record.fields.user_data);
results.html(user_data.username);
It’s as simple as that! The fields in user_data are available with dot notation so you can do a condition like if(user_data.authenticated) { do something };
and that will work because “authenticated” is a real true/false value.
Using loadjson()
Another method to use JSON is to load that JSON data directly from an external location. This location can be:
- A local file on the drive
- An external URL such as an online service
- A PlanetPress Workflow process that returns JSON data.
The loadjson() function is available in the Designer module, in scripts. It simply requires the URL or path to the JSON file:
var json_variables = loadjson(“file:///c:/jsondata/variables.json”);
var json_users = loadjson(“http://www.example.com/api/getusers/all”);
Accessing the data inside those variables will be the same as the example above - you could just access json_variables.base_url
, for example.
For more information on JSON data, check out Wikipedia: JSON.