Need a way to convert a sensor state or literal string to a JSON object

I’ve searched for a way to do this, so if it’s already possible somehow, I’d love to know!

I would love a way to convert a literal string that contains well-formed JSON to a JSON object within a template. My particular use case was trying to pass a JSON object that I created within a script as a parameter to another script. The child script can only see it as a string, yet it is still well-formed JSON. There doesn’t seem to be an easy way to then access the values in the JSON without resorting to string manipulation functions, which would be error-prone at best.

I thought I had found something with the “|tojson” filter, but that merely escapes special characters in the string so it can be included in a JSON string, it does NOT parse the string as JSON.

Thanks!

Not sure if you use node red, but you should give it a try if not! Pretty sure this node will do what you want in node red. Right?
I cant write code for squat but node red allows me to do things that would be impossible for me without it. Hope this helps.

I don’t know if you saw this thread Trying to understand JSON parsing. The upshot is that state stores everything as a string so no matter how well-formed the JSON may be it will handled as a string. Perhaps parameters get the same treatment and are passed as strings only.

I found this post by Petro indicating an attribute can be used to store a JSON object. This information was given to an individual who was making a custom component therefore could create attributes. Otherwise, I don’t believe one can readily create new attributes (certain MQTT components can accept custom attributes via their JSON_attributes_topic). Anyway, it’s all moot because you need to pass the JSON object as a script parameter and not as an entity attribute.

Yeah! It was that thread that was the motivation for this post. But when I went looking for it, I couldn’t find it again.

I thought about somehow using the json_attributes_topic field of an MQTT sensor, but that only parses the JSON down one level. Any sub objects are rendered as a single attribute with a JSON string as a value. And then we have the initial problem again anyway.

Edit: I don’t have Node Red installed.