feat(editor): Add toJsonString to string extensions (#13798)

This commit is contained in:
Dana
2025-03-11 10:34:09 +01:00
committed by GitHub
parent 9c040ee5a5
commit 4e93ffda8b
2 changed files with 30 additions and 0 deletions

View File

@@ -159,6 +159,10 @@ function length(value: string): number {
return value.length; return value.length;
} }
export function toJsonString(value: string): string {
return JSON.stringify(value);
}
function removeMarkdown(value: string): string { function removeMarkdown(value: string): string {
let output = value; let output = value;
try { try {
@@ -700,6 +704,23 @@ isNotEmpty.doc = {
], ],
}; };
toJsonString.doc = {
name: 'toJsonString',
description:
'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 JavaScripts JSON.stringify().',
section: 'edit',
returnType: 'string',
docURL:
'https://docs.n8n.io/code/builtin/data-transformation-functions/strings/#string-toJsonString',
examples: [
{
example: 'The "best" colours: red\nbrown.toJsonString()',
evaluated: '"The \\"best\\" colours: red\\nbrown"',
},
{ example: 'foo.toJsonString()', evaluated: '"foo"' },
],
};
extractEmail.doc = { extractEmail.doc = {
name: 'extractEmail', name: 'extractEmail',
description: description:
@@ -877,6 +898,7 @@ export const stringExtensions: ExtensionMap = {
isUrl, isUrl,
isEmpty, isEmpty,
isNotEmpty, isNotEmpty,
toJsonString,
extractEmail, extractEmail,
extractDomain, extractDomain,
extractUrl, extractUrl,

View File

@@ -313,6 +313,14 @@ describe('Data Transformation Functions', () => {
expect(() => evaluate('={{ "No JSON here".parseJson() }}')).toThrowError('Parsing failed'); expect(() => evaluate('={{ "No JSON here".parseJson() }}')).toThrowError('Parsing failed');
}); });
test('.toJsonString should work on a string', () => {
expect(evaluate('={{ "test".toJsonString() }}')).toEqual(JSON.stringify('test'));
expect(evaluate('={{ "The \\"best\\" colours: red\\nbrown".toJsonString() }}')).toEqual(
JSON.stringify('The "best" colours: red\nbrown'),
);
expect(evaluate('={{ "".toJsonString() }}')).toEqual(JSON.stringify(''));
});
test('.toBoolean should work on a string', () => { test('.toBoolean should work on a string', () => {
expect(evaluate('={{ "False".toBoolean() }}')).toBe(false); expect(evaluate('={{ "False".toBoolean() }}')).toBe(false);
expect(evaluate('={{ "".toBoolean() }}')).toBe(false); expect(evaluate('={{ "".toBoolean() }}')).toBe(false);