Template node javascript object evaluation - stringify

I am trying to use a template node to setup a javascript object, eg.:

I want to stringify it to make it available via a http endpoint.
So I use a function node;

msg.payload = JSON.stringify(msg.payload)
return msg

output:

""{name: \"John Doe\"}""

This is not a valid JSON string.

If I use a function node and directly use an object:

let test = {name: "John Doe"}
msg.payload = JSON.stringify(test)
return msg;

output:

"{"name":"John Doe"}"

This is correct.

What is happening when the data leaves the template node that it does not evaluate to an object ?

How have you configured the Template node? The default is to send the contents as plain text. If you want it to parse the template as JSON and to send the Object, you need to change the "Output as" option to "Parsed JSON".

But if you want it to do that, then you need to ensure the Template is valid JSON. Your current contents is not JSON - you need to put quotes around name:

{ "name": "John Doe"}

What if I want to make the "object" from the template node available in a function node as an object ? (not necessarily as JSON)

The Template node is for generating text.

As a convenience, if the text is valid JSON, then the node has an option to parse the generated text from JSON to a JavaScript object. If you didn't use that option, this is the same as putting a JSON node after the Template node.

So the only way to have the Template node send a JavaScript object is for you to enter JSON in the Template node and have it parse it for you.

Ok thanks for making clear what I suspected.

If you actually want it as a JSON string to make it available via a http endpoint, then your original config should do that, except that you need to put valid JSON in the template. So in the template put {"name": "Fred"} and don't tell the template to convert it from JSON to an object. In the following function node you don't need the JSON.stringify() call as it is already JSON.

Yes understood:

What if I want to make the "object" from the template node available in a function node as an object ? (not necessarily as JSON)

I think i can solve this by using some regex.

Then again, setting up the template node with proper JSON is probably easier :')