Assistance with parsing of JSON w/Jinja

HI all,

Seeking some assistance with parsing the following JSON in an MQTT sensor value template so that I can test against the section in bold only.

tele/sonoff/RF_Bridge/RESULT = {“RfRaw”:{“Data”:“AA B1 04 012C 028A 00B4 26AC 38090909290918181919090909090919191919181809 55”}}

So far I have this:

  - platform: mqtt
    name: "Bedroom Fan"
    icon: mdi:radar
    state_topic: "tele/sonoff/RF_Bridge/RESULT"
    value_template: >-
      {% if value_json.RfRaw.Data is equalto "XXXXXX"
        on
      {% else %}
        off
      {% endif %}

Does anyone have any examples where a string is parsed with a certain delimiter into an array?

Thanks!

Put this in the Template Editor and it will extract the second to last number (i.e. the long number) :

{% set x = "AA B1 04 012C 028A 00B4 26AC 38090909290918181919090909090919191919181809 55" %}
{% set y = x.split(" ") %}
{{ y[-2:-1] | join }}

Now to adapt it for your requirements, it’ll look something like this. I haven’t tried this so it may require further adjustments:

value_template: >-
  {% set y = value_json.RfRaw.Data.split(" ") %}
  {% set z = y[-2:-1] | join %}
  {% if z is equalto "XXXX" %}
  on
  {% else %}
  off
  {% endif %}

If you wish, you can combine it into one statement:

{% set z = value_json.RfRaw.Data.split(" ")[-2:-1] | join %}

Thanks so much @123!

that seems overkill. that’s going to get the 2nd to last item as a list, then combine it with nothing. If he wants the 2nd to last item as a string, then [-2] will suffice without the join.

Thanks! [-2] is so much neater!

I’m still a neophyte at slicing. My initial mistake was believing I needed the : in [ : ] so that led to [-2:-1] which doesn’t produce a string but a list element. I slapped on a join to convert it to a string. So my initial mistaken assumption led me to an unnecessarily long-winded solution!

The revised version is much cleaner:

{% set z = value_json.RfRaw.Data.split(" ")[-2] %}

Yeah, it only produces a list because it’s slicing instead of getitem. When you access an item in a list via a single value it returns the single value as the object that it is. It’s very useful.