Cannot parse a json array in a template

Not sure if this is the right to post… But I’m having some issues and have been fighting with this thing for like 3 hours now.

I’ve got a custom software that can submit some json at certain events. Here’s an example of that json body:

{ "data": {"message": "This is a test message", "items": ["Test Item"]}}

When this json body gets sent to my webhook, I have a service to send me a notification on my phone with the following template:

service: notify.mobile_phone
data:
  title: Test App
  message: >-
    {{ trigger.json.data.message }} | Items: {{ trigger.json.data.items | join (", ") }}

I get the error in my logs: Error rendering data template: TypeError: ‘builtin_function_or_method’ object is not iterable

So troubleshooting, I change my template to:

service: notify.mobile_phone
data:
  title: Test App
  message: >-
    {{ trigger.json.data.message }} | Items: {{ trigger.json.data.items }}

and get the message:
This is a test message | Items:

No items… Okay, so now to troubleshoot the entire data:

service: notify.mobile_phone
data:
  title: Test App
  message: >-
    '{{ trigger.json.data }}'

which returns me:

'{'message': 'This is a test message', 'items': ['Test Item']}'

So I’m super confused, why can’t this thing parse the json coming back from the API? I even confirmed in the API logs that it’s most definitely a json object being sent over correctly… So I’m at a loss on why I’m getting errors or no data at all from Home Assistant.

Ideally, I’d get:
This is a test message | Items: Test Item

With multiple items being like:
This is a test message | Items: Test Item, Test Item 2, Test Item 3

items is a reserved keyword, as it is a dictionary method. Always use bracket notation for safety, so:

trigger.json['data']['items']

and similar. You can test things like this in the Template Editor. Here, I fake up the trigger variable first:

{% set trigger = {"json": {"data": {"message": "This is a test message", "items": ["Test Item"]}}} %}
1: {{ trigger.json }}
2: {{ trigger.json.data }}
3: {{ trigger.json.data.items }}
4: {{ trigger.json.data.items() }}
5: {{ trigger.json.data['items'] }}
6: {{ trigger.json['data']['items'] }}

4 Likes

oh jeez, I had no idea that HA was using python as the template language too - totally thought they had their own parsing going on. This would have made my template learning journey so much quicker to know LOL. Thank you for mentioning that. I didn’t even have to read the rest of your message as soon as I clicked that link and saw it was Python. I knew HA was in general Python, but that did not come to mind at all when working on these templates.

Again, thanks!