Allow ast.eval_literal in python_scripts

python_script component does not allow any imports. This makes it very limited in data processing.
Such a basic use-case as JSON data processing (e.g. received from a webhook or MQTT) within a python string is not possible.
When I pass webhook JSON data using a template to the script - all I get is not a dictionary but a dictionary string instead. And this is fine as long as there is some way to process such string.
Unfortunately imports are forbidden in scripts. So is the eval keywork. However there is a safer alternative for eval. It’s ast.eval_literal. However it requires import - so again not possible to use it.

I propose to add a feature to allow execution of ast.eval_literal within python_script scripts.
This would solve things like this: How to pass trigger.value_json (Python dict) to python_script?
…and many others caused by another Ha limitation - templates rendered always as strings instead of native Python types.

It’s puzzling why the json module has been excluded from python_script. It prevents one from easily converting a JSON list or dictionary into a python list or dictionary. This makes it awkward to access items in something like this:

[ {"name": "John", "address": "abc123"}, {"name": "Mary", "address": "xyz890"} ]

you should be able to convert that to a python object and then use something like value_json[1].name to get Mary’s name. Unfortunately, you can’t because the json module is missing and no modules can be imported into the sandboxed python_script environment. :man_shrugging:

1 Like

Exactly. I think this approach is just too restrictive. Either ast.eval_literal should be available or some alternative solution should be provided within HA. Otherwise this makes data processing capabilities in python_script really poor.