It is best to use variable names that have correct meaning otherwise you will always get confused or someone trying to read your code will (both probably).
So your first assignment (which should use let not var by the way) is a string. So it should be something like this:
let myJson = '{"desc":"","label":"123_CH07_RxA04"}'
try {
myJson = JSON.parse(myJson)
} catch (e) {
// Do sometihng if needed if the parse fails - JSON.parse will ALWAYS occasionally fail, bet on it
}
Which makes more sense and myJson now actually contains a JS object as expected.
However, not sure why you want to turn that string into an object and then write it to CSV, that will likely always be an issue. You WANT your JSON to be a string before trying to write it to a CSV. So if anything you should be doing all this the other way around. Start with the JS object, use JSON.stringify (which also needs a try/catch around it) and then write that to CSV.
Yes, but I'd like to get the exact same content is what we can see in the original string...
I could get rid of the " " " from the string, but I need in the end also "" when there is no value for any of the key ( as we can see in desc in this specific case...)
Don't know how I can handle this, if I use just a space in desc then I'd get a " " in the final csv....
Sorry, I'm lost now. A CSV is a defined schema and complex strings HAVE to be escaped otherwise you don't have a working CSV. The double double-quotes are REQUIRED in the CSV. Without them you cannot use the CSV anywhere, it won't work.
To prove the case, try with the quotes in place and then manually edit one of the entries. In both cases, open the csv in Excel or similar and see what happens.
That is not a CSV. It looks like a TSV (Tab separated). That would actually be easier to work with for your data probably. But it isn't a CSV. You can work with that in Node-RED I think - still using the incorrectly named "CSV" node, just set it to use tabs instead of comma's as the separator. TSV does not need the double quoting as long as you don't try to include tabs in your fields.
Well, in the end I made a small piece of code by myself in a function node directly connected to a file write node, and now gets the proper result in the target file :
const separator = ";";
let csvlines = ""
var columns = (Object.keys(msg.payload[0]).join(separator));
for (let index = 0; index < msg.payload.length; index++) {
msg.payload[index].descriptor = JSON.stringify(msg.payload[index].descriptor);
var line = (Object.values(msg.payload[index]).join(separator) + "\n" );
csvlines = csvlines + line;
}
//node.warn("csvContent" + csvlines)
msg.columns = columns;
msg.payload = msg.columns + "\n" + csvlines;
return msg;