Search code examples
jsonfreemarker

How to get values from JSON in Freemarker


So I have a JSON file or html request that looks like this:

tuStatus:   
          0:
             references:    […]
             progressBar:   {…}
             changeDeliveryPossible:    false
             arrivalTime:   {…}
             tuNo:  "(here is usually a package number)"
             owners:    […]
             history:   
                     0: 
                        date:   "2021-11-11"
                        time:   "12:52:04"
                        evtDscr:    "Package has been deliverd."
                        address:    
                                 countryName:   "Niederlande"
                                 countryCode:   "NL"
                                 city:  ""

I allways want to acess the historypart at position 0and check if the package has been deliviered. To check this I need to read out the string at evtDscr. If the package has been delivered yet, I want to access the date and time strings. How can I acess the variables via freemarker language?


Solution

  • In the comment you say that you get the whole JSON as a single string. So then, assuming you have recent FreeMarker version, you can use ?eval_json:

    <#assign someParsed = someString?eval_json>
    

    And now you use expressions like someParsed.tuStatus[0].history[0].evtDscr == "Package has been deliverd.". (Though I guess the evtDscr value is not very reliable... like if somebody fixes the typo in it (should be "delivered"), the comparison won't work.)