Trying to create JSON structure for MQTT

Objective
Pass solar power data from HA via MQTT to Victron system using JSON data structure.

The receiver is expecting a data structure like this:

{
    "pv": {
        "power": 0.0,
        "voltage": 0.0,
        "current": 0.0,
        "energy_forward": 0.0,
        "L1": {
            "power": 0.0,
            "voltage": 0.0,
            "current": 0.0,
            "frequency": 0.0,
            "energy_forward": 0.0,
        },
    }
}

I am attempting to create this using a template helper. So far I have assembled the
basic data thus: (Note: the values for pv are the same as L1)

I am completely stuck creating the final output. This is the best I have so far:

{% set pwr ={ 'power':states('sensor.growatt_grid_active_power')} %}
{% set voltage ={ 'voltage':states('sensor.growatt_output_voltage')} %}
{% set current ={ 'current':states('sensor.growatt_output_current')} %}
{% set energy ={ 'energy_forward':states('sensor.growatt_todays_generation')} %}

{% set first ={ 'pv' :[ pwr , voltage , current , energy ]} %} 
{% set second ={ 'L1' :[ pwr , voltage , current , energy ]} %}

{% set output = first , second    %}
{{ output|tojson }}

Any help or pointers to some documentation on this very welcome.
Thankyou.

Format your code correctly. Then you’re likely to get people helping you because they can copy and paste it.

Edit: that’s better :slightly_smiling_face:

Note that pv and L1 should be dictionaries but you are creating them as lists.

Just do it directly:

{% set output = {
  "pv": {
    "power": states('sensor.growatt_grid_active_power'),
    "voltage": states('sensor.growatt_output_voltage'),
    "L1": {
    }
  }|tojson
%}

… with the other values filled in appropriately.

1 Like

Thank you for your suggestion, I think I’ve improved the formatting.
Is that what you were suggesting?
Eric

1 Like

This creates an array, but the JSON you posted originally is what Jinja would consider to be a dict.

Personally I would just do:

{
  "pv": {
    "power": {{ states('sensor.growatt_grid_active_power') }},
    "voltage": {{ states('sensor.growatt_output_voltage') }},
    "current": {{ states('sensor.growatt_output_current') }},
    "energy_forward": {{ states('sensor.growatt_todays_generation') }},
    "L1": {
      "power": {{ states('sensor.growatt_grid_active_power') }},
      "voltage": {{ states('sensor.growatt_output_voltage') }},
      "current": {{ states('sensor.growatt_output_current') }},
      "energy_forward": {{ states('sensor.growatt_todays_generation') }}
    }
  }
}

You don’t need to convert to JSON, just output something that is valid JSON in the structure you want.

1 Like