I am getting an output JSON from an HTTP Request, but I just cant seem to find a way of parsing it into a JSON so I can save it to a database. I have read dozens of articles, but havent found anyone with a similar problem. Tried all snippets shared on posts (regardin JSON parsing issues), tried split, tried edit fields,
After some trial and error testing, I noticed what needs to happen for it to work properly. I need to get rid of: \n, \ (from ") and the first and last "
I tried with javascript, but it looks like it is not finding matching strings and simply returns the input.
You can simply try to parse your string to JSON by using JSON.parse().
On your Javascript node, just give a name to your array and try to parse the content.
thank you very much, I really appreciate you taking yout time to help… but this code didn’t quite work for me (tried .first() as well)
const myData = [{"data": $input.all()}]
return JSON.parse(myData[0].data);
-------------
"[object Object]" is not valid JSON [line 3]"
SyntaxError
However, once I mapped the http request output, I managed to solve with this JS:
// load input as string
let str = JSON.stringify($input.all());
// clean input
str = str.replaceAll('\\n','');
str = str.replaceAll('\\r','');
str = str.replaceAll('\\','');
str = str.replaceAll(' ',' ');
// http request added quotes to data array ( { "data": "[{},{}]" } )
// so the code below removes it. Since it is always a fixed
// position, I indexed all quotes i string and removed these two
let quoteIndexes = [];
for (let i = 0; i < str.length; i++) {
if (str[i] === '"') {
quoteIndexes.push(i);
}
}
if (quoteIndexes.length < 5) {
console.log("Not enough quotes to remove");
return str;
}
let fifthIndex = quoteIndexes[4];
let fifthFromLastIndex = quoteIndexes[quoteIndexes.length - 5];
//remove first quote
let result = str.slice(0, fifthIndex) + str.slice(fifthIndex + 1);
if (fifthFromLastIndex > fifthIndex) {
fifthFromLastIndex -= 1;
}
// remove second quote
result = result.slice(0, fifthFromLastIndex) + result.slice(fifthFromLastIndex + 1);
//console.log(result);
return JSON.parse(result);
But I still believe this is simply a jerry-rig and there’s probably a much easier way for accomplishing it in n8n…