Strings to JSON array

Can you please tell me how to collapse the content of the Input text, e.g.:

Line1, Line2, Line3, ..., LineN

to JSON array of strings, e.g.:

"{"Array_name":["String1","String2","String3",...,"StringN"]}"

to send through MQTT with automation.

And vice versa - how to pass JSON array of strings, e.g.

"{"Array_name":["String1","String2","String3",...,"StringN"]}"

to Input text, e.g.

Line1, Line2, Line3, ..., LineN

Thank you.

2 Likes

Use templates:

Open your Home Assistant instance and show your template developer tools.

Json to string:

{% set a = {"Array_name":["String1","String2","String3","StringN"]} %}
{{ a.Array_name | join(', ') }}

Drop the first line and replace a with value_json in your MQTT sensor’s value_template.

String to json:

{% set a = 'Line1, Line2, Line3, ..., LineN' %}
{{ { "Array_name": a.split(', ') } | to_json }}

Drop the first line and replace a with the state of your input text and put the template in payload_template when calling mqtt.publish.

2 Likes

Thank you.