Twig: Sorting JSON

From Version 3.3 on the PRO-Version can sort JSON by using a Extension to twig (“parser=twig” needed in the Shortcode!). This is done like this:
  • Check the structure of your JSON by
  • Identify the Array you want to display. Arrays are collections of other Arrays or Objects (which are in fact converted to arrays)
  • Write twig-code to display the array: Just display it now, we add the sorting later…). This should be something like this (unknown JSONArrayName?):
    {% for item in JSONArrayName %}
    fieldA: {{item.fieldA}}  / fieldB: {{item.fieldB}} / fieldC: {{item.fieldC}}<br>
    {% endfor %}
  • Now we add the sorting:
    {% for item in JSONArray | sortbyjsonfield("fieldA##fieldB,desc##fieldC,,num") %}
    fieldA: {{item.fieldA}}  / fieldB: {{item.fieldB}} / fieldC: {{item.fieldC}}<br>
    {% endfor %}
  • Syntax:
    sortbyjsonfield(STRING) with a special string like “fieldname” (sort field as string from A to Z),
    “fieldname,desc” (sort field as string from Z to A),
    “fieldname,,num” (sort field as number from -infinity to infinity),
    “fieldname,desc,num” (sort field as number from infinity to -infinity)

    “,” and “##” are delimiters (if those are part of the fieldname this won’t work – contact developer in this case to make the delimiter dynamic).