Convert dictionary to JSON in python_script

This is sample python_script with dictionary in payload.

topic = 'test/topic'
payload = {
    'value1': 12,
    'name': 'test'
}

service_data = {
    'topic': topic,
    'payload': payload,
    'retain': False,
    'qos': 0
}

hass.services.call('mqtt', 'publish', service_data, False)

This give me an error:

TypeError: payload must be a string, bytearray, int, float or None.

How to convert payload to JSON without import json module?

Why can’t you import json?

It isn’t possible to import modules in the python_script component https://www.home-assistant.io/components/python_script/

I don’t have any direct experience, but I see examples on GitHub of people doing this. Is there a difference?

I don’t see anything at that link that suggests you can’t import stuff. What makes you think that?

The scripts are run in a sandboxed environment

And this Error import modules python script

When I add import to script I have this error:

Error executing script: __import__ not found
Traceback (most recent call last):
  File "c:\users\maciek\appdata\local\programs\homeassistant\lib\site-packages\homeassistant\components\python_script.py", line 166, in execute
    exec(compiled.code, restricted_globals, local)
  File "test.py", line 1, in <module>
ImportError: __import__ not found

Yesterday I tied this:

value1 = 'test1'
value2 = 'test2'
payload = '{\"value1\": \" + value1 + \", \"value2\": \" + value2 + \"}'

and it works but with big dictionaries it’s very uncomfortable.

payload = {
'value1': 12,
'name': 'test'
}

service_data = {
'topic': topic,
'payload': payload,
'retain': False,
'qos': 0
}

Thanks, I spent some time finding a solution … I finally solved it this way
add payload = '{}'.format(payload).replace('\'', '\"')

In your example

payload = {
'value1': 12,
'name': 'test'
}

payload = '{}'.format(payload).replace('\'', '\"')

service_data = {
'topic': topic,
'payload': payload,
'retain': False,
'qos': 0
}
1 Like