Twig: Sorting JSON

The PRO Version can sort JSON by using a twig-extension (“parser=twig” needed in the Shortcode or set in the plugin template!). 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}}
    {% 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}}
    {% 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)
    • “fieldname,,date” and “fieldname,desc,date” (sort field as date)

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