Strange behavior of my simple API

I'm trying a simple API, and I have a strange behavior with the result.
The result is JSON formatted, the data come from a DB query.
The result has unwanted escape characters:

"{"type":[ {"sensor":"temperature", "unit":"celsius"}, {"sensor":"humidity", "unt":"relative"} ]}"

To be sure that this isn't due to the DB response, I've modified the payload. Now it's static.
So, i'm sure, the msg.payload, passed to http request, is without escape characters:
{"type":[ {"sensor":"temperature", "unit":"celsius"}, {"sensor":"humidity", "unt":"relative"} ]}
checked with debug node, but te response from http request is still with escape characters.
How to remove them?

Thanks, Fabrizio

Do you mean the double quotes round the outside? Can you feed the response into a debug node and screenshot what you see and paste it here so we can fully understand what you mean please.

This is te payload of http request:

and this is the result:

The result adds \ as escape character.

And also the headres of the http response:

This happens because your property msg.payload.d_type is a JSON encoded string. That means it stays as a String when msg.payload is itself JSON encoded and returned.

Add a JSON node and configure it to parse msg.payload.d_type to an object before the HTTP Response node.

Thanks knolleary for your suggestion.

I had already done it, but without results.

Here the modified flow with the added JSON node.

Even changing the action, I have the same result. :roll_eyes:

In your original screenshot, msg.payload was an object with a property called d_type that needed parsing.

In this most recent screenshot, msg.payload is an array of objects. That means the path to the element you need to convert is msg.payload[0].d_type.

Ok, sorry, my mistake. I've forgotten the array index. payload[0].d_type
Now a new question: how to apply to all elements of the array?
Thanks.

One option would be to add a Split node before the JSON node and a Join node afterwards. Use their default configuration and change the JSON node back to msg.payload.d_type.

Another option would be to replace the JSON node with a Function node:

msg.payload = msg.payload.map(function(v) {
   v.d_type = JSON.parse(v.d_type);
   return v;
});
return msg;

I've adopted the second solution. I'm a bungler, so it has taken me more time than really need, but it works.
Thanks,
Fabrizio

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.