Transforming pure string "body" from Webhook

Hello,

I didn’t find the exact same situation that causes problems in this community forum, so I dare to share with you my problem :slight_smile:

I’ve a n8n webhook that receives “Text/Plain” data via POST method.

This webhook gives me JSON formatted data, with of course header informations, empty param, empty query, and a pure string body :

[
{
"headers": {
"host": "URL",
"user-agent": "Go-http-client/1.1",
"content-length": "120",
"accept-encoding": "gzip",
"content-type": "text/plain; charset=utf-8",
"x-forwarded-for": "IP",
"x-forwarded-host": "URL",
"x-forwarded-port": "443",
"x-forwarded-proto": "https",
"x-forwarded-server": "09e57e6daf5b",
"x-real-ip": "IP"
},
"params": {
},
"query": {
},
"body": "{bin:"ABCDEF",time:1653913941.385,val1:40,val2:50,val3:60,val4:70,val5:80}"
}
] 

I’d like to convert the string body into JSON.

I found community posts sharing nice Functions module code trying to convert the string in body but it always fails. I think that’s because there are no { ... } for the body line.

I can retrieve params (or query, even though they are empty) using items[0].json.params but using items[0].json.body fails, so using JSON.parse() function isn’t even possible.

Do you have suggestion(s) for me please ?

Thank you !!

Hey @hachann, welcome to the community!

It looks like your body doesn’t contain valid JSON but rather a JavaScript-like object definition. You technically could try the approaches suggested here on StackOverflow, but these would execute code not directly under your control (which is a big no-go).

If there’s any way of getting a proper JSON object via webhook that’d be much preferred!

Still, if you want to go down that rabbit hole, here’s an example workflow parsing your data:

This workflow implements the suggestion from the SO post linked above and produces the below result:

Is this what you had in mind?

Thank you for this procedure, I’m testing it right now.

When you suggest to get a proper JSON object via webhook, I think I did explore every other option with the origin of the HTTP POST Request toward n8n. It’s a pure plain/text, and I can’t interfere with that sadly. Do you know of a procedure for 8n8 to deal with that ?

Hey @hachann, this isn’t so much a n8n-specific problem as a problem with the data format not complying to the JSON standard. You might be best of with a regular expression if your data structure doesn’t change. Do you need all values or just ABCDEF from your example?