Search code examples
javascripthtmljsonpostmanpostman-testcase

Visualize multi-level response object as Table in Postman


I would like to visualize the data below in Postman Tests as a Table with product, price and quantity in columns and Items in rows. There might be multiple shippingGroups.

{
   ...
   "companyGroups": [
        {
            ...
            "shippingGroups": [
                {
                    "id": 1,
                    "items": [
                        {
                            "product": "Product A",
                            "price": 2,
                            "quantity": 1,
                        },
                          {
                            "product": "Product B",
                            "price": 4,
                            "quantity": 4,
                        }

                    ],
                    ...
            ]
        }
    ],

I have trouble using the {{#each response???}} referring to items within multiple level objects. Expected format should be something like :

   <table>
        <tr>
            <th>Product</th>
            <th>Price</th>
            <th>Quantity</th>
        </tr>

        {{#each response???}}
            <tr>
                <td>{{???product}}</td>
                <td>{{???price}}</td>
                <td>{{???quantity}}
            </tr>
        {{/each}}
    </table>

More info on Postman Table Visualizing Response here


Solution

  • Given your response example, you could use something like this:

    const template = `
       <table>
            <tr>
                <th>Product</th>
                <th>Price</th>
                <th>Quantity</th>
            </tr>
    
            {{#each responseData}}
            {{#each items}}
                <tr>
                    <td>{{product}}</td>
                    <td>{{price}}</td>
                    <td>{{quantity}}
                </tr>
            {{/each}}
            {{/each}}
        </table>
    `;
    
    let responseData = []
    
    _.each(pm.response.json().companyGroups, (item) => {
        _.each(item.shippingGroups, (nestedItem) => {
            responseData.push(nestedItem)
        })
    })
    
    pm.visualizer.set(template, { responseData })
    

    This is just a rough example and would need to be refactored but it shows that you can show the response data in the table.