Rest api for json object

Hi

I am trying to include a json data source in HA with the rest api. I am partially successful with that, but still a couple of questions remain. The json data source looks like this:

{ "version": "0.8.0", "generator": "vzlogger", "data": [ { "uuid": "ca24687e-0481-4770-94d5-657d7db65f66", "last": 1574848158398, "interval": -1, "protocol": "sml", "tuples": [ [ 1574848158398, 366.60000000000002 ] ] }, { "uuid": "3beb68cf-a2aa-4ff5-bd66-58cb0d3bd58a", "last": 1574848158398, "interval": -1, "protocol": "sml", "tuples": [ [ 1574848158398, 3656154.8000000003 ] ] }, { "uuid": "2e3485a7-f210-4796-9ddb-f8769892c227", "last": 0, "interval": -1, "protocol": "sml" }, { "uuid": "5e8a172a-c778-45c1-8b5d-597629cd4953", "last": 0, "interval": -1, "protocol": "sml" } ] }

I am interested in the uuids and the second value of the tuples. Thus I wrote in my sensor.yaml the following code for each of the uuids:

  - platform: rest
    resource: http://192.168.205.201:8080/
    value_template: > 
      {% for i in value_json.data %}
         {% if i.uuid == "3beb68cf-a2aa-4ff5-bd66-58cb0d3bd58a" %}
           {{ i.tuples[0][1] }}
         {% endif %}
      {% endfor %}

    method: GET
    name: "Zählerstand Haushaltsstrom"
    unit_of_measurement: "Wh"

It (kind of) works, but I have two questions:

  • Is the for loop really necessary or is there a more elegant (and faster) way to solve the problem?
  • How do I divide by 1000 to get kWh (instead of Wh) and round to one or two decimal places?

Thx

Thorsten

Not sure about the for loop (maybe a regex_findall_index?), but for kWh:

{{ i.tuples[0][1]|int / 1000 }}

value_json.data contains a list with four items. The item you want has uuid = 3beb68cf-a2aa-4ff5-bd66-58cb0d3bd58a and is the second item in the list. If you know that it is always the second item in the list then you can use this:

  - platform: rest
    resource: http://192.168.205.201:8080/
    value_template: "{{ (value_json.data[1].tuples[0][1] / 1000) | round(1) }}"

However, if the desired item’s position can be anywhere in the list, then you will have to find it first (using a for-loop):

  - platform: rest
    resource: http://192.168.205.201:8080/
    value_template: > 
      {% for i in value_json.data if i.uuid == "3beb68cf-a2aa-4ff5-bd66-58cb0d3bd58a"%}
        {{ (i.tuples[0][1] / 1000) | round(1) }}
      {% endfor %}

EDIT
Correction.
Replaced:
/ 100
with:
/ 1000

1 Like

/ 1000

1 Like

Oops! Thank you! Will correct ASAP.

1 Like

Thx a lot for your help! As I cannot guarantee that the UUIDs will always be in the same order, I have to use the for loop. Thank you for making that clear!

Dividing and rounding also works now. Sorry for this trivial issue but yesterday I was not able to get it to work. Maybe I forgot to reboot or whatever…

1 Like