Parse JSON in helper gives error, works in sensor

I have working sensor, it gives value as expected

    - name: "e-Up!_battery_soc"
      unique_id: "eup_battery_soc"
      state_topic: "wican/e-up/can/rx"
      state_class: "measurement"
      value_template: >-
        {% if value_json.frame[0].id == 2029 %}
          {% set PID = value_json.frame[0].data[3] %}
          {% if PID == 140 %}
          {% set AA = value_json.frame[0].data[4] %}
            {{ ((AA - 24)/2.15) | round(0) | int }}
        {% endif %}
        {% endif %}

But if i try to set it up as helper like this

{% set value_json = states('sensor.e_up_raw_data') %}
{% if value_json.frame[0].id == 2029 %}
{% set PID = value_json.frame[0].data[3] %}
  {% if PID == 140 %}
  {% set AA = value_json.frame[0].data[4] %}
    {{ ((AA - 24)/2.15) | round(0) | int }}
{% endif %}
{% endif %}

It doesnt work, if i put it in template editor it gives me error UndefinedError: 'str object' has no attribute 'frame'
My raw_data sensor gives exactly same data as mqtt topic, setup like this

    - name: "e-Up!_raw_data"
      unique_id: "eup_raw_data"
      state_topic: "wican/e-up/can/rx"
      value_template: "{{ value }}"

I would like to get it working atleast in template editor, easier to test different calculations etc
Is it possible to get it working, do i have something wrong in my setup.
MQTT message is:

{
  "bus": "0",
  "type": "rx",
  "ts": 7119,
  "frame": [
    {
      "id": 2029,
      "dlc": 8,
      "rtr": false,
      "extd": false,
      "data": [
        4,
        98,
        2,
        140,
        128,
        170,
        170,
        170
      ]
    }
  ]
}
1 Like

That will return a string. That’s why the error message complains about UndefinedError: 'str object'.

If the sensor’s value looks like it’s in JSON format, try this:

{% set value_json = states('sensor.e_up_raw_data') | from_json %}

Thank you very much, that worked.

1 Like

Is it possible for mqtt sensor or helper to get value from two different messages.
Right now i use two mqtt sensors one for each message, then i have helper to combine that data.
So that i could use only one sensor and combine data.

Here is data from message 1

{
  "bus": "0",
  "type": "rx",
  "ts": 41032,
  "frame": [
    {
      "id": 1914,
      "dlc": 8,
      "rtr": false,
      "extd": false,
      "data": [
        16,
        10,
        98,
        42,
        182,
        0,
        145,
        0
      ]
    }
  ]
}

and here is message 2

{
  "bus": "0",
  "type": "rx",
  "ts": 41062,
  "frame": [
    {
      "id": 1914,
      "dlc": 8,
      "rtr": false,
      "extd": false,
      "data": [
        33,
        120,
        0,
        25,
        0,
        170,
        170,
        170
      ]
    }
  ]
}

These messages arrive at different timestamp, first message 1, then message 2, when looking from history log