The idea is:
If I try to save a very complex string in a JSON object (e.g. html document) I will often get an error JSON parameter needs to be valid JSON [item 0]
Can you add an expression function that will escape any invalid characters from JSON? e.g. here is an online tool that does it for me. MDN docs on JSON object specs
My use case:
I need to store HTML docs in fields and then insert them into HTTP requests JSON body.
I think it would be beneficial to add this because:
Escaping characters is hard to do manually, so please add a convenience function to accomplish it.
Are you willing to work on this?
yes, if you help me setup dev environment
You can use the existing .toJsonString()
or just JSON.stringify
E.g. this JSON {"count":1,"name":"Test n8n"}
becomes {\"count\":1,\"name\":\"Test n8n\"}
1 Like
That’s not always possible. Consider the following, where I’m getting a string out of a JSON for the comment body:
{
"$jira_comment_id": {{ $json.jira_comment_id }},
"$issue_key": {{ $json.issue_key.quote() }},
"$updated": {{ $json.updated.toDateTime().toISO().quote() }},
"$comment_body": {{ $json.comment_json.parseJson().comment.body.replaceSpecialChars().quote().replaceAll('\n','\\n').replaceAll('\t','\\t') }},
"$author_name": {{ $json.comment_json.parseJson().comment.author.displayName.quote() }},
"$author_email": {{ ($json.comment_json.parseJson().comment.author.emailAddress || '').quote() }},
"$jira_author_id": {{ $json.comment_json.parseJson().comment.author.accountId.quote() }}
}
In this case, $json.comment_json.parseJson().comment.body
is a string. If I do $json.comment_json.parseJson().comment.toJsonString()
then it will return far more data than I actually want. But the excerpted $json.comment_json.parseJson().comment.body
is no longer safe to pass unless I perform several .replaceAll()
s on it.
It would really be much better if we had a .escape()
and .unescape()
set of functions (or similar).
The way I handle anything like this now is to put the WHOLE thing inside an expression and use a JS object. I highly recommend doing this to avoid any serialisation issues e.g.:
{{
{
"$jira_comment_id": $json.jira_comment_id,
"$issue_key": $json.issue_key,
"$updated": $json.updated.toDateTime().toISO(),
"$comment_body": $json.comment_json.parseJson().comment.body.replaceSpecialChars(),
"$author_name": $json.comment_json.parseJson().comment.author.displayName,
"$author_email": ($json.comment_json.parseJson().comment.author.emailAddress || ''),
"$jira_author_id": $json.comment_json.parseJson().comment.author.accountId,
}
}}
1 Like
That’s certainly a way to do it, and I might adopt that for future flows. But I still think a JsonEscapeString and JsonUnescapeString would be very useful as convenience functions; especially given how many ways JSON data might be entering an n8n flow (apis, spreadsheets, pasted in, etc.)