diff --git a/packages/grafana-ui/src/components/JSONFormatter/json_explorer/helpers.test.ts b/packages/grafana-ui/src/components/JSONFormatter/json_explorer/helpers.test.ts new file mode 100644 index 00000000000..f4d388acdb3 --- /dev/null +++ b/packages/grafana-ui/src/components/JSONFormatter/json_explorer/helpers.test.ts @@ -0,0 +1,45 @@ +import { formatString } from './helpers'; + +describe('JSONFormatter helpers', () => { + describe('escapeString', () => { + it("does not escape strings that don't contain quotes", () => { + const input = 'hello world'; + const expected = 'hello world'; + + const result = formatString(input); + expect(result).toEqual(expected); + }); + + it('does not escape strings that contain single quotes', () => { + const input = `'hello world'`; + const expected = `'hello world'`; + + const result = formatString(input); + expect(result).toEqual(expected); + }); + + it('does escapes strings that contain one double quote', () => { + const input = `"hello world`; + const expected = `\\"hello world`; + + const result = formatString(input); + expect(result).toEqual(expected); + }); + + it('does escapes strings that contain two double quotes', () => { + const input = `"hello world"`; + const expected = `\\"hello world\\"`; + + const result = formatString(input); + expect(result).toEqual(expected); + }); + + it('does escapes a string that looks like JSON', () => { + const input = `{"hello": "world"}`; + const expected = `{\\"hello\\": \\"world\\"}`; + + const result = formatString(input); + expect(result).toEqual(expected); + }); + }); +}); diff --git a/packages/grafana-ui/src/components/JSONFormatter/json_explorer/helpers.ts b/packages/grafana-ui/src/components/JSONFormatter/json_explorer/helpers.ts index 64f40ddcfb1..72c410a1feb 100644 --- a/packages/grafana-ui/src/components/JSONFormatter/json_explorer/helpers.ts +++ b/packages/grafana-ui/src/components/JSONFormatter/json_explorer/helpers.ts @@ -4,8 +4,8 @@ /* * Escapes `"` characters from string */ -function escapeString(str: string): string { - return str.replace('"', '"'); +export function formatString(str: string): string { + return str.replace(/\\/g, '\\\\').replace(/"/g, '\\"'); } /* @@ -62,7 +62,7 @@ export function getValuePreview(object: object, value: string): string { } if (type === 'string') { - value = '"' + escapeString(value) + '"'; + value = '"' + formatString(value) + '"'; } if (type === 'function') { // Remove content of the function