Working with JSON

Creating a JSON file

This piece of code grabs the latest packages from our site and creates a JSON file.

  1. $response.setHeader("Content-Type""application/json")  
  2.   
  3. #set($limit = '10')  
  4. #set($orderBy='modDate desc')  
  5. #set($query="+structureName:NAMEOFSTRUCTURE")  
  6.   
  7. #set ($listItems = "")  
  8. #set ($listItems = $dotcontent.pull($query,$limit,$orderBy))  
  9.   
  10. #set ($myList = $contents.getEmptyList())  
  11. #set ($mymap = $contents.getEmptyMap())  
  12.   
  13. ## Do a loop through the structure and populate a title (or other field)
  14.     #set($dummy = $mymap.put("title","$list.title"))  
  15. ##end
  16. #set($myjson = $json.generate($mymap))     
  17. #set($dummy = $myList.add($myjson))  
  18.   
  19. ##Now output the contents you created above into a JSON format:
  20. {"contentlets":$myList}  

Displaying results from a JSON page

Now we have created the JSON file. This is how we then extract and display the information from the JSON file.

  1. <ul>  
  2.   
  3.     #set ($myjson = "")  
  4.     #set ($myjson = $json.fetch('http://www.url.org/feeds/json-packages.dot'))  
  5.     #set ($contentList = $myjson.get('contentlets'))  
  6.      
  7.     #if ($contentList.size() > 0)  
  8.      
  9.         #foreach($content in $contentList)  
  10.      
  11.             <li>  
  12.              
  13.                 <h3><a href="/link/">$!{esc.xml($content.get('title'))}</a></h3>  
  14.                  
  15.                 <div class="image-wrapper">  
  16.                  
  17.                     <img src="/application/assets/images/img.png" alt="">  
  18.      
  19.                     <a href="/link/">  
  20.                          
  21.                         <img src="$content.get('image')" width="244" alt="">  
  22.      
  23.                     </a>  
  24.                      
  25.                 </div>  
  26.                      
  27.             </li>  
  28.          
  29.         #end  
  30.          
  31.     #end  
  32.   
  33. </ul>  
comments powered by Disqus