Visualization - Iterating through object properties using {{#each}}

Hey folks,

I have managed to use the #each handlebars keyword to iterate through JSON arrays, but what if I wanted to iterate through the properties of an object (not an array) instead?

For example, say my response has an object “flags”, with a bunch of key/value pairs, basically. So, something like:

{
    "flags" : {
        "flag1": { /* nested properties */ },
        "flag2": { /* blah blah blah */ }
    }
}

Per some information I have seen on the handlebars site and forums, I should still be able to use {{#each response.flags}} and use {{@key}} for the key, and {{this}} to reference properties underneath the key.

However, when using a handlebars template in Postman, this does not appear to work. No rows are returned. I know that #each on objects was a later addition, but it appears to be in handlebars as of 2015, so it should work at this point.

Is the Postman implementation of these templates actually handlebars, or a roll-your-own thing?

Note - as a workaround, I can just use raw JS code and build the HTML table myself that way, using for (var key in response.flags), but I thought it would be nice to make use of templates where possible.

Thoughts, comments, suggestions?

Well, crap. I stumbled across the solution quite by accident while working on a standard array implementation. Seems that I simply failed to pass the response as a function call.

So instead of:

pm.visualizer.set(template, { response: pm.response.json() });

I was sending it as a value:

pm.visualizer.set(template, { response: pm.response.json });  // No parentheses after json.

Duh. Anyway, it works now. Hopefully others will #LFMF.

1 Like

Not sure if you need it, but in case you were trying to visualize your response as a table, you can use this template to visualize any JSON/CSV response as a table (without writing any code - since it’s pre-written :smile:):

3 Likes

I did see that pop up in search results. Haven’t tried any templates as of yet. Looks like as good a time as any to dive in. :slight_smile: Thanks!

1 Like