From a262a0a5f5f24081e672622217198216d0ffc00b Mon Sep 17 00:00:00 2001 From: YuShifan <894402575bt@gmail.com> Date: Wed, 15 Nov 2023 15:03:59 +0800 Subject: [PATCH] feat(utils): add is json string func --- packages/utils/lib/__test__/jsonUtils.test.ts | 28 ++++++++++++++++++- packages/utils/lib/jsonUtils.ts | 15 ++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/packages/utils/lib/__test__/jsonUtils.test.ts b/packages/utils/lib/__test__/jsonUtils.test.ts index 6200456..0547cc8 100644 --- a/packages/utils/lib/__test__/jsonUtils.test.ts +++ b/packages/utils/lib/__test__/jsonUtils.test.ts @@ -1,4 +1,4 @@ -import { parseJSONSafely, stringifyObjSafely } from '../jsonUtils' +import { parseJSONSafely, stringifyObjSafely, isJSONString } from '../jsonUtils' import { describe, it, expect } from 'vitest' describe('parseJSONSafely', () => { @@ -28,3 +28,29 @@ describe('stringifyObjSafely', () => { expect(output).toEqual(input) }) }) + +describe('isJSONString', () => { + it('should return true for valid JSON strings', () => { + const input = '{"a":1,"b":2,"c":3}' + const output = isJSONString(input) + expect(output).toEqual(true) + }) + + it('should return false for invalid JSON strings', () => { + const input = '{a:1,b:2,c:3}' + const output = isJSONString(input) + expect(output).toEqual(false) + }) + + it('should return false for non-string inputs', () => { + const input = 123 + const output = isJSONString(input as any) + expect(output).toEqual(false) + }) + + it('should return false for null', () => { + const input = null + const output = isJSONString(input as any) + expect(output).toEqual(false) + }) +}) diff --git a/packages/utils/lib/jsonUtils.ts b/packages/utils/lib/jsonUtils.ts index 43fb60d..134d527 100644 --- a/packages/utils/lib/jsonUtils.ts +++ b/packages/utils/lib/jsonUtils.ts @@ -28,3 +28,18 @@ export const stringifyObjSafely = (obj: Record, tabSpaces?: number) return 'stringify error' } } + +/** + * Checks if a given string is a valid JSON string. + * @param str - The string to be checked. + * @returns A boolean indicating whether the string is a valid JSON string or not. + */ +export const isJSONString = (str: string): boolean => { + if (typeof str !== 'string') return false + try { + const obj = JSON.parse(str) + return typeof obj === 'object' && obj !== null + } catch (e) { + return false + } +}