Skip to content

Commit 4e93ffd

Browse files
authoredMar 11, 2025
feat(editor): Add toJsonString to string extensions (#13798)
1 parent 9c040ee commit 4e93ffd

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed
 

‎packages/workflow/src/Extensions/StringExtensions.ts

+22
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,10 @@ function length(value: string): number {
159159
return value.length;
160160
}
161161

162+
export function toJsonString(value: string): string {
163+
return JSON.stringify(value);
164+
}
165+
162166
function removeMarkdown(value: string): string {
163167
let output = value;
164168
try {
@@ -700,6 +704,23 @@ isNotEmpty.doc = {
700704
],
701705
};
702706

707+
toJsonString.doc = {
708+
name: 'toJsonString',
709+
description:
710+
'Prepares the string to be inserted into a JSON object. Escapes any quotes and special characters (e.g. new lines), and wraps the string in quotes.The same as JavaScript’s JSON.stringify().',
711+
section: 'edit',
712+
returnType: 'string',
713+
docURL:
714+
'https://docs.n8n.io/code/builtin/data-transformation-functions/strings/#string-toJsonString',
715+
examples: [
716+
{
717+
example: 'The "best" colours: red\nbrown.toJsonString()',
718+
evaluated: '"The \\"best\\" colours: red\\nbrown"',
719+
},
720+
{ example: 'foo.toJsonString()', evaluated: '"foo"' },
721+
],
722+
};
723+
703724
extractEmail.doc = {
704725
name: 'extractEmail',
705726
description:
@@ -877,6 +898,7 @@ export const stringExtensions: ExtensionMap = {
877898
isUrl,
878899
isEmpty,
879900
isNotEmpty,
901+
toJsonString,
880902
extractEmail,
881903
extractDomain,
882904
extractUrl,

‎packages/workflow/test/ExpressionExtensions/StringExtensions.test.ts

+8
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,14 @@ describe('Data Transformation Functions', () => {
313313
expect(() => evaluate('={{ "No JSON here".parseJson() }}')).toThrowError('Parsing failed');
314314
});
315315

316+
test('.toJsonString should work on a string', () => {
317+
expect(evaluate('={{ "test".toJsonString() }}')).toEqual(JSON.stringify('test'));
318+
expect(evaluate('={{ "The \\"best\\" colours: red\\nbrown".toJsonString() }}')).toEqual(
319+
JSON.stringify('The "best" colours: red\nbrown'),
320+
);
321+
expect(evaluate('={{ "".toJsonString() }}')).toEqual(JSON.stringify(''));
322+
});
323+
316324
test('.toBoolean should work on a string', () => {
317325
expect(evaluate('={{ "False".toBoolean() }}')).toBe(false);
318326
expect(evaluate('={{ "".toBoolean() }}')).toBe(false);

0 commit comments

Comments
 (0)
Please sign in to comment.