Sorting returned data

Having trouble figuring out how to sort my returned JSON data. I’m trying to sort the data by the $element.modifier values. But everything I’ve tried in inserting sort has returned errors. Where should I be doing this?

(I tried putting {{ range sort . $element.modifier }} after the initial range but that didn’t work either.)

JSON data

{
    "props": {
        "NAME": {
            "value": "16px",
            "desc": "",
            "css": "padding",
            "modifier": "primary",
            "function": "",
            "color": "",
            "group": "",
            "element": "content",
            "breakpoint": "",
            "state": "",
            "environment": "",
            "hex": ""
        },
        ...
    }
}

Shortcode template:

{{ $pattern := .Get "pattern" }}
{{ $data := index .Site.Data.design_tokens $pattern }}
{{ range $index, $element := $data.props }}
Lines with {{ $element.modifier }} and more...
{{{ end }}

Does this thread helps?

Thank you for replying, but it doesn’t in the sense that I’m trying to sort the (kind of) already sorted returned data. I really just want to display the data according to one field alphabetically, or ideally, multiple fields concurrently.

Thinking outside the hugo box (and noting that you’re trying to it with hugo directly), you might look into jq, which is a utility for manipulating json data. I have found use for it in many projects. https://stedolan.github.io/jq/

Thanks @RickCogley. I’ll take a look at it.

Still would be very surprised if this wasn’t fairly easy with Hugo, however.

Try:

{{ range $index, $element := sort $data.props "modifier" }}
3 Likes

@moorereason Yes! Thank you! This is the simple solution I’ve been looking for, and can’t believe I didn’t try. (or if I did, I likely missed some syntax bug).