Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a JSON array using Apache VTL(Velocity templating language)

I'm using Apache VTL in one of my project. The project uses Apache velocity to generate PDFs out of JSON data. I have one use case where the JSON is a JSON array. Example JSON is as below.

[
  {
    "key1": "value1",
    "key2": "vaalue2"
  },
  {
    "key1": "value1",
    "key2": "vaalue2"
  }
]

If I need to loop through each of these objects using VTL, how do I achieve the same as Velocity templates access every object by a key name?

like image 366
Sudeep Moharana Avatar asked Nov 04 '16 09:11

Sudeep Moharana


People also ask

What is VTL template?

VTL is a logical template language that gives you the power to manipulate both the request and the response in the standard request/response flow of a web application, using techniques such as: Default values for new items. Input validation and formatting. Transforming and shaping data.

What is JSONPath parse?

JSONPath is an expression language to parse JSON data. It's very similar to the XPath expression language to parse XML data. The idea is to parse the JSON data and get the value you want.

What is Velocity template language?

Velocity is a server-side template language used by Confluence to render page content. Velocity allows Java objects to be called alongside standard HTML. If you are are writing a user macro or developing a plugin you may need to modify Velocity content.


1 Answers

I had a similar case and this is my solution,
in your model put json keys as a map
here is the code:

  [
   #foreach($key in $json.keySet())
      { 
        "$key" : "$json.get($key)" 
       }  
      #if( $foreach.hasNext ), #end
   #end
  ]
like image 85
JavaSheriff Avatar answered Oct 19 '22 22:10

JavaSheriff