Skip to content

Commit

Permalink
feat(utils): add is json string func
Browse files Browse the repository at this point in the history
  • Loading branch information
ysfscream committed Nov 15, 2023
1 parent 874faac commit a262a0a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
28 changes: 27 additions & 1 deletion packages/utils/lib/__test__/jsonUtils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { parseJSONSafely, stringifyObjSafely } from '../jsonUtils'
import { parseJSONSafely, stringifyObjSafely, isJSONString } from '../jsonUtils'
import { describe, it, expect } from 'vitest'

describe('parseJSONSafely', () => {
Expand Down Expand Up @@ -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)
})
})
15 changes: 15 additions & 0 deletions packages/utils/lib/jsonUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,18 @@ export const stringifyObjSafely = (obj: Record<string, any>, 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
}
}

0 comments on commit a262a0a

Please sign in to comment.