7

We are having a requirement to generate JSON objects combined with html fragments out of the pages created in Tridion. We need to publish these to another application which will further process the generated HTML+JSON chunks. I need some suggestions on how we can achieve this through templates as i am fairly new to JSON. All the content is static in nature and we are using Tridion 2011 SP1.

6

A google search for "tridion json" gives me quite a few decent results, particularly this one.

Serializing to JSON is not that hard - except when dealing with Rich Text fields and when deciding what to do about Tridion content delivery features (like dynamic linking) that you may have to (re)implement on the delivery side.

I've had some troubles in the past too with deserializing, especially dates.

2
  • Nice example link, Nuno. I think the example demonstrates quite well how in a C# TBB it can be achieved. I've also seen similar things done with the Razor mediator too.
    – robrtc
    Jan 19 '15 at 9:27
  • I also used to have problems with dates. Quite often I didn't even get to the deserializing part.
    – Dominic Cronin
    Jan 19 '15 at 13:48
2

Depending on how many different types of component presentations you need to produce a simple DWT might work (one per uniquely different type of component presentation required):

<div>
  <h2>@@Component.Fields.title@@</h2>
  <p>@@Component.Fields.intro@@</p>
</div>

<script>
  var model = {
    "title":"@@Component.Fields.title@@",
    "intro":"@@Component.Fields.intro@@"
  };
</script>

If your serialization rules are generic you could use an assembly TBB to serialize your component to JSON format and inject it into the output (at the end of the fragment; or by replacing a well-known placeholder).

Keep in mind you will have to produce valid javascript code so if you use double quotes as a string terminator for your values you will need to escape double quotes and newline characters or your generated JSON will be invalid.

I believe a hybrid solution would be a good match in your case where you store the HTML structure of your HTML fragment in a DWT and the code to serialize your component to JSON in an assembly TBB.

As Nuno states you might also need to handle dynamic component links and binary links; either your application will have to resolve these using the linking API provided by the Tridion CD libraries or via the Tridion Content Delivery webservice or you will have to statically resolve these at template render time. If you have no component link fields this is obviously not a problem.

Rich text fields should not provide a challenge as the same escaping rules apply as for normal fields (escape newlines and double/single quotes depending on what you are using as a string terminator).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.