When working with nested data structures in Traffic Parrot mock responses, you may encounter unexpected behaviour with nested {{#each}} loops, mainly when using the @index variable. Here's how to handle this common issue.
The Problem
Consider a request containing nested arrays, such as a list of customers, each with multiple contact methods:
{
"customerId": "ABC123XYZ",
"details": [
{
"name": { "first": "John" },
"contacts": [
{
"region": "123",
"identifier": "5551234567",
"category": "PRIMARY"
},
{
"region": "123",
"identifier": "5551234568",
"category": "SECONDARY"
}
]
}
]
}
When using nested {{#each}} loops without named loop variables, the @index variable may reference the outer loop's index instead of the intended inner loop's index.
The Solution
To correctly handle nested loops, always use named loop variables in your {{#each}} statements:
{{#each (jsonPath request.body '$.details') as |details| }}
{
"customerId": "{{ jsonPath request.body '$.customerId' }}",
"status": "SUCCESS",
"statusDescription": "Customer record created",
"details": [
{{#each details.contacts as |contact| }}
{
"region": "{{ contact.region }}",
"identifier": "{{ contact.identifier }}",
"category": "{{ contact.category }}"
}{{#unless @last}},{{/unless}}
{{/each}}
]
}{{#unless @last}},{{/unless}}
{{/each}}
Best Practices
- Always name your loop variables in
{{#each}}statements - Use descriptive variable names that reflect the data being iterated
- Remember to handle comma separators using
{{#unless @last}},{{/unless}}

No comments:
Post a Comment