Can't get value from json (builtin_function_or_method object has no element)

templates
Tags: #<Tag:0x00007f1b9a4d48f8>

#1

Hello,

I want to grab some data from a REST Api but it doesn’t work. So I’ve started testing the JSON string in the Template Editor like this:

{% set my_test_json = {
  "items": [
   {
    "statistics": {
      "test1": "73",
      "test2": "0",
    }
   }
  ]
} %}

#{{ my_test_json.items[0].statistics.test1 }}

What i get is the error message

Error rendering template: UndefinedError: builtin_function_or_method object has no element 0

But the JSON access looks valid for me. What does builtin_function_or_method mean? Is items a blocked keyword, so I can’t use such a response?

Thanks in advance,
best regards,
Florian


#2

I’ve created a workaround for now via the command_line sensor, but I’m still wondering why it doesn’t work with the restful sensor.

command: curl -sS {{ states.sensor.secret_url.state }} | jq -r '.items[0].statistics.test1'


#3

You’re basically creating a Python dictionary, and a Python dictionary has a method named items. So you’d have to do this:

{% set my_test_json = {
  "items": [
   {
    "statistics": {
      "test1": "73",
      "test2": "0",
    }
   }
  ]
} %}

{{ my_test_json["items"][0].statistics.test1 }}

#4

yay it works now, thank you :slight_smile:

I like the “rest way” better than my cmdline workaround.