Sudeep Moharana
Sudeep Moharana

Reputation: 61

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?

Upvotes: 6

Views: 4028

Answers (1)

JavaSheriff
JavaSheriff

Reputation: 7687

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
  ]

Upvotes: 1

Related Questions