Undocumented 'to_json' Modifier in Movable Type 5 for Direct JSON-format Output

| 2 Comments | No TrackBacks |
This Japanese blog post alerted me to the existence of an undocumented 'to_json' modifier in Movable Type 5.  There is a well documented list of global modifiers like encode_html, trim, capitalize... available here, but 'to_json' seems to be missing from that list or any other place in the documentation.  What does it do?
JSON (JavaScript Object Notation) is a popular data format that is used by many applications to store/transmit/receive hierarchically organised information, like the properties of a list of items.  The 'to_json' attribute in Movable Type lets you output data stored in array and hash variables directly in JSON format, without the need for additional loop tags or template code.  

Consider this snippet of template code:

<mt:setvarblock name="item{color}">blue</mt:setvarblock>
<mt:setvarblock name="item{id}">5</mt:setvarblock>
<mt:setvarblock name="item{status}">OK</mt:setvarblock>

<mt:var name="item" to_json="1">

This will result in:

{"color":"blue","status":"OK","id":"5"}

Or with a simple array:

<mt:var name="items[0]" value="zero">
<mt:var name="items[1]" value="one">
<mt:var name="items[2]" value="two">
<mt:var name="items[3]" value="three">

<mt:var name="items" to_json="1">

Which results in:

["zero","one","two","three"]

It even works recursively:

<mt:setvarblock name="item{color}">blue</mt:setvarblock>
<mt:setvarblock name="item{id}">5</mt:setvarblock>
<mt:setvarblock name="item{status}">OK</mt:setvarblock>

<mt:var name="items{first}" value="$item">

<mt:setvarblock name="item{color}">red</mt:setvarblock>
<mt:setvarblock name="item{id}">7</mt:setvarblock>
<mt:setvarblock name="item{status}">INACTIVE</mt:setvarblock>

<mt:var name="items{second}" value="$item">

<mt:var name="items" to_json="1">

This results in:

{"first":{"color":"blue","status":"OK","id":"5"},"second":{"color":"red","status":"INACTIVE","id":"7"}}

Neat!  I'm sure this will come in handy if you ever need to export large amounts of data from Movable Type in JSON format...


No TrackBacks

TrackBack URL: http://www.movabletips.com/cgi-bin/mt/mt-tb.cgi/2018

2 Comments

Thanks for the tip, Maarten. For more on how to use the JSON in a MT template, I'd recommend the following article:

http://thecomposingstick.com/2010/03/using-jquery-with-movable-type.html

It's truly very difficult in this busy life to listen news on Television, therefore I simply use world wide web for that purpose, and get the most recent news.

Leave a comment


Movable Type Help?

"Can my Movable Type issue or project be taken care of by a professional?" Yes It Can Be! Contact YesItCan.be

Tags

Powered by Movable Type 5.2.2