Forum Discussion

pp_01's avatar
pp_01
Mentor
7 years ago

Reordering a nested JSON in freemarker.

Hey guys. Is there any way so that a nested JSON response can be reordered? I want to rearrange the position of objects from the way I'm getting to a different manner. Suppose my JSON and my requirement is something like what is written below. Is there any way to achieve this. Any code example will be of great help. Thanks in advance.

 

{
    "alphabets": {
        "a": "1",
        "b": "2",
        "c": "3",
        "d": "4",
        "e": "5",
        "f": "6",
        "g": "7"        
    },
    "h": "8",
    "i": "9",
    "j": "10",
    "k": "11",
    "l": "12"
}

and I want the output (text) to be like - 
    h: 8
    i: 9
    j: 10
    k: 11
    l: 12
    alphabets:
        a: 1
        b: 2
        c: 3
        d: 4
        e: 5
        f: 6
        g: 7 

 

  • pp_01 Yes, you can achieve this. 

     

    e.g  You have stored all the json inside a variable. You need keys and reverse function to achieve the result. 

    <#assign json = {//your json here} /> 
    <#list json?keys?reverse as key> ${key} - ${json[key]} </#list>

4 Replies

  • pp_01 Yes, you can achieve this. 

     

    e.g  You have stored all the json inside a variable. You need keys and reverse function to achieve the result. 

    <#assign json = {//your json here} /> 
    <#list json?keys?reverse as key> ${key} - ${json[key]} </#list>
  • pp_01's avatar
    pp_01
    Mentor
    7 years ago

    Hey Tariq. Thanks for answering the query. It is working for the reverse part of the JSON but it is still giving this has evaluated to an extended_hash error for the Nested JSON. Any idea how that can be done?

    Thanks.

     

  • pp_01's avatar
    pp_01
    Mentor
    7 years ago

    I got the answer after a lil bit of trying. Thank you so much for your help. 

  • pp_01 - good job. This code just reorder the top level key. And as I have printed the key anr value, you might be getting error as you have nested JSON inside a value.