Formatting JSON for MQTT Publish call

My end goal is to send a randomly selected text string via MQTT Publish.

So far I have this working but it breaks if the strings have spaces (nothing gets spoken by the wall panel).

payload_template: '{"speak": {{ ["test1”, "test2”] | random }}}'
topic: wallpanel/kitchen/command

to_json (doc) seems like the a possible solution if I could write it to use random like the above example but I can’t even get a basic example to work with MQTT Publish. At least not under Developer Tools > Services. Just gives syntax errors and won’t let me submit. I believe the jinja {% %} syntax is only available for templates?

{% set test = {'speak': 'test'} %}
payload_template: {{ test|to_json }}
topic: wallpanel/kitchen/command

At this point maybe making a template using the to_json filter (with random selection integrated somehow) and then pulling that into the MQTT Publish call is what I need?

Open to any suggestions that might help me reach my end goal.

Getting somewhere. Have this working under Developer Tools > Template

{% set test = {'speak': ["test 1", "test 2", "test 3"] | random } %}
payload_template: '{{ test|to_json }}'
topic: wallpanel/kitchen/command

Think I just need to put the pieces together in configuration.yaml and the automation that makes the MQTT Publish call.

Please correct me if I’m on the wrong track or there’s an easier way.

Also, I believe there’s a way to pull these random strings from a separate file rather than wedging them all into the jinja section?

have you read this in the docs?

payload must be a string. If you want to send JSON then you need to format/escape it properly. Like:

topic: home-assistant/light/1/state
payload: "{\"Status\":\"off\", \"Data\":\"something\"}"

Not sure what you’re getting at. Escaping is not the issue in this case. My test when using payload (not shown) all worked fine just by using proper quoting (combination of single / double quotes like in my example), no \ escapes necessary.

For example with payload_template

This works (proper quoting so escapes are not required)

payload_template: '{"speak":{{ ["test1", "test2"] | random }}}'
topic: wallpanel/kitchen/command

This does not (spaces added)

payload_template: '{"speak":{{ ["test 1", "test 2"] | random }}}'
topic: wallpanel/kitchen/command

This also does not (escaped as per your example) but does work without the spaces in the test strings

payload_template: "{\"speak\":{{ [\"test 1\", \"test 2\"] | random }}}"
topic: wallpanel/kitchen/command

Also note that I switched to payload_template because it allows for the {{ }} syntax and random, etc. to_json is supposed to be a simpler, cleaner way of generating json for such things I believe it’s just that it cannot be used in Developer Tools > Services or Automations, etc or rather the jinja portion {% %} cannot, only in config files, I think?