While doing some preparation for a hackathon on client-side templating (ie javascript in the browser) on our upcoming SDL Tridion MVP retreat, I created a simple component JSON serializer TBB. This basically takes the TOM.NET Component object and converts it into a JSON format which is friendly for Javascript templating frameworks like Knockout.
This is just a proof-of-concept, so it doesn’t cover everything – and the focus is on keeping the JSON structure as shallow and simple as possible. The output should be something like the following:
{ "id":1693,
"publication":69,
"title":"Lets create templates with Javascript",
"summary":"By publishing content as JSON, retrieving it using webservices and using a framework like Knockout, we can do templating client-side.",
"image":{
"url":"/Images/json_logo_tcm69-6630.png",
"metadata":{"alt":"JSON Logo"}
},
"pubdate":"2013-09-19T09:29:23Z",
"metadata":{
"standard":{
"keywords":"this, page, is, cool",
"location":{
"id":1901,"key":"NL","title":"Netherlands","description":"Netherlands"
}
}
}
The full source code of the TBB is shown below, a few things worth noting are:
For easy access, there is no fields, or content container element for content fields – they are added directly to the root element, metadata fields are added to a sub element; metadata
For component link fields, which link to MM component, we publish the binary and add published url and metadata to the output(see the image field example above). For non MM component link fields, just the component uri is output
For keyword fields, we add the keyword id, key, title and description.
For date fields, we convert to JSON friendly ISO 8601 format (this will save some pain)
For embedded schema fields, we build the substructure you would expect (see the standard metadata field above)
Rich Text fields are skipped – these tend to be very heavy and serialize messily, and I want to keep my JSON lightweight – I don’t intend to use RTF in my JS templates anyway – we will use traditional templating methods for that.
One thought on “Quick TBB – Serialize Component as JSON”
Pingback: Client-side Templating with JSON, oData and Angular | SDL Tridion Developer