Node-Red JSON Format Issue

Hi, I can subscribe to my event in Node-Red Particle-SSE node, the data comes through fine except the data field is sent as a string.

Example:

{"data":"{ \"temp\": 22.00, \"voltage\": 4.05 }","ttl":60,"published_at":"2020-07-06T13:45:09.157Z","coreid":"xxxxxxxxxxxxxxxxxxxxxxx","name":"osVoltage"}

See how the data is a string;

"data":"{ \"temp\": 22.00, \"voltage\": 4.05 }",

It means I need to do some extra parsing to split that out. Does anyone know why it’s doing that?

Thanks,
Alex

When you encode JSON and send it from a function, it will always be escaped, as you see here. This allows sending data that includes special JSON characters (ie if you wanted to send data that included " characters), and is a security feature.

It is a simple matter of decoding the string into a JSON object in your endpoint (ie JSON.parse() in javascript)

Hi, is not easy also i’m not familiar with Node-Red
(but is pretty much js).

I was able to parse your data field strings in pure js maybe this can help or give you some light.

<!DOCTYPE html>
<html>
<body>

<h2>convert JSON value String to JSON</h2>



<script>

var txt = '{"data":"{"\temp\": 22.00, "\voltage\": 4.05 }","ttl":60,"published_at":"2020-07-06T13:45:09.157Z","coreid":"xxxxxxxxxxxxxxxxxxxxxxx","name":"osVoltage"}'; 


String.prototype.removeCharAt = function (i) {
    var tmp = this.split(''); // convert to an array
    tmp.splice(i - 1 , 1); // remove 1 element from the array (adjusting for non-zero-indexed counts)
    return tmp.join(''); // reconstruct the string
}







var obj1 = JSON.stringify(txt);  // convert to string
var obj2 = obj1.replace(/\\/g, ''); // remove all backslash
var obj3 = obj2.replace("u000b", "v"); // for some reason after removing backshlashes "v" is changing to "u000b" so replaced back to "v"
var obj4 = obj3.slice(1, obj3.length - 1); // remove " " " which is on first and last position

var obj5 = obj4.removeCharAt(9); // remove " " " on pos 9
var obj6 = obj5.removeCharAt(42); // remove " " " on pos 42
var finall =  JSON.parse(obj6);

console.log("step 1 obj1",obj1);
console.log("step 2 obj2",obj2);
console.log("step 3 obj3",obj3);
console.log("step 4 obj4",obj4);
console.log("step 5 obj5",obj5);
console.log("fliall", finall);
console.log("temp value from Data", finall.data.temp);

</script>

</body>
</html>

removeCharAt function is from here also you don’t need var obj1,obj2,obj3…etc as you can do this “on-flight”
This is just to show the conversion idea step by step
and here some results: