From 7b87ea82d3d63420e548743c5a84a073f0cdad22 Mon Sep 17 00:00:00 2001 From: Jun Yang Date: Tue, 21 Mar 2023 23:52:56 +0800 Subject: [PATCH] feat: JSON format by `space` in `json` filter --- src/filters/misc.ts | 4 ++-- src/util/timezone-date.spec.ts | 2 +- test/integration/filters/misc.spec.ts | 5 +++++ 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/filters/misc.ts b/src/filters/misc.ts index ca4421be9b..806c58ea1a 100644 --- a/src/filters/misc.ts +++ b/src/filters/misc.ts @@ -9,8 +9,8 @@ export function Default (this: FilterImpl, value: T1, de return isFalsy(value, this.context) ? defaultValue : value } -export function json (value: any) { - return JSON.stringify(value) +export function json (value: any, space = 0) { + return JSON.stringify(value, null, space) } export const raw = { diff --git a/src/util/timezone-date.spec.ts b/src/util/timezone-date.spec.ts index 94dcb1ad29..c1aa76c663 100644 --- a/src/util/timezone-date.spec.ts +++ b/src/util/timezone-date.spec.ts @@ -26,7 +26,7 @@ describe('TimezoneDate', () => { }) it('should support .toLocaleTimeString()', () => { const date = new TimezoneDate('2021-10-06T00:00:00.001+00:00', -480) - expect(date.toLocaleTimeString('en-US')).toBe('8:00:00 AM') + expect(date.toLocaleTimeString('en-US')).toMatch(/^8:00:00\sAM$/) expect(() => date.toLocaleDateString()).not.toThrow() }) it('should support .toLocaleDateString()', () => { diff --git a/test/integration/filters/misc.spec.ts b/test/integration/filters/misc.spec.ts index 63d846e595..bc6f92117d 100644 --- a/test/integration/filters/misc.spec.ts +++ b/test/integration/filters/misc.spec.ts @@ -24,5 +24,10 @@ describe('filters/object', function () { it('should stringify number', async () => expect(await liquid.parseAndRender('{{2 | json}}')).toBe('2')) it('should stringify object', async () => expect(await liquid.parseAndRender('{{obj | json}}', { obj: { foo: 'bar' } })).toBe('{"foo":"bar"}')) it('should stringify array', async () => expect(await liquid.parseAndRender('{{arr | json}}', { arr: [-2, 'a'] })).toBe('[-2,"a"]')) + it('should support space', () => { + const scope = { obj: { foo: 'foo', bar: 'bar' } } + const result = '{\n "foo": "foo",\n "bar": "bar"\n}' + expect(liquid.parseAndRenderSync('{{obj | json: 4}}', scope)).toBe(result) + }) }) })