Search code examples
velocityxwiki

howto add entries in JSON array with velocity


With velocity I declare my array like this:

#set ($MyArray={
  'Index1':{'Field1':'value1','field2':'value2'},
  'Index3':{'Field1':'A value','field2':'Another value'}
})

How can I add an "Index2" entrie by example:

'Index2':{'Field1':'A new value','field2':'Another new value'}"

or can I modify a value ('Index 1'.field2' by example)?

Thxs for any help


Solution

  • $MyArray is not an array variable but a map (Thxs to Marius): http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

    Then the answer is:

    #set ($MyArray={
      'Index1':{'Field1':'value1','field2':'value2'},
      'Index3':{'Field1':'A value','field2':'Another value'}
    })
    $MyArray.getClass().getName()
    * Original map
    $jsontool.serialize($MyArray)
    * I Modify the 'Index3' entrie:
    #set ($discard=$MyArray.put('Index3',{'Field1':'A modified value','field2':'Another modified value'}))
    $jsontool.serialize($MyArray)
    * I add the 'Index2' entrie:
    #set ($discard=$MyArray.put('Index2',{'Field1':'Addon value','field2':'Another addon value'}))
    $jsontool.serialize($MyArray)