Home > OS >  How to apply Jinja `length` logic to nested JSON array?
How to apply Jinja `length` logic to nested JSON array?

Time:04-30

Riffing on this question, how do I drill even further into an nested array and apply some length logic?

Goal: If the PositionsHeld array has more than 1 entry, I want to separate the values with a comma , but not for the last entry.

Example:

JSON snippet:

{
    "Employers": [
        {
            "EmploymentType": "Food Service",
            "Employer": "Test Brew",
            "EmployerURL": "",
            "StartMonth": 9,
            "StartYear": 2020,
            "EndMonth": null,
            "EndYear": null,
            "City": "Olympia",
            "State": "WA",
            "PositionsHeld": [
                {"Position": "Barista"},
                {"Position": "Asst. Manager"}
            ]
        },
        {
            "EmploymentType": "Food Service",
            "Employer": "The Steakhouse",
            "EmployerURL": "https://www.steakmill.com/",
            "StartMonth": 7,
            "StartYear": 2019,
            "EndMonth": 1,
            "EndYear": 2020,
            "City": "Milton",
            "State": "WA",
            "PositionsHeld": [
                {"Position": "Busser"}
            ]
        }
    ]
}

HTML w/Jinja snippet:

{% for e in data.Employers %}

<h3>
{% for p in e.PositionsHeld %} 
    {% if p|length > 1 %}     <-- Here is the crux of question -->
        {{ p.Position }} ,    <-- Want to add a "," if needed BUT NOT TO THE FINAL POSITION-->
        else {{ p.Position }} 
    {% endif %} 
{% endfor %}
</h3>

{% endfor %}

CodePudding user response:

Here's what you're looking for with this:

{% for e in data.Employers %}
    <h3>
        {% for p in e.PositionsHeld %}
            {% if not loop.last %}{{ p.Position }}, {% else %}{{ p.Position }}{% endif %}
        {% endfor %}
    </h3>
{% endfor %}

Or, a more condensed version (I like this way better as it's simple):

{% for e in data.Employers %}
    <h3>
        {{ e.PositionsHeld | join(',', attribute="Position") }}
    </h3>
{% endfor %}
  • Related