Skip to content

Commit

Permalink
feat(utils): add json utils
Browse files Browse the repository at this point in the history
  • Loading branch information
ysfscream committed Nov 15, 2023
1 parent 3239d7a commit 1377eea
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
37 changes: 37 additions & 0 deletions packages/utils/lib/__test__/jsonUtils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { parseJSONSafely, stringifyObjSafely } from '../jsonUtils'
import { describe, it, expect } from 'vitest'

describe('parseJSONSafely', () => {
it('should correctly parse a JSON string', () => {
const input = '{"a":1,"b":2,"c":3}'
const output = parseJSONSafely(input)
expect(output).toEqual({ a: 1, b: 2, c: 3 })
})

it('should return undefined when parsing an invalid JSON string', () => {
const input = '{a:1,b:2,c:3}'
const output = parseJSONSafely(input)
expect(output).toBeUndefined()
})
})

describe('stringifyObjSafely', () => {
it('should correctly stringify an object', () => {
const input = { a: 1, b: 2, c: 3 }
const output = stringifyObjSafely(input)
expect(output).toEqual('{"a":1,"b":2,"c":3}')
})

it('should return the input if it is a string', () => {
const input = 'a string'
const output = stringifyObjSafely(input as any)
expect(output).toEqual(input)
})

it('should return "stringify error" when an error occurs during stringification', () => {
const circularObj = {}
circularObj['self'] = circularObj
const output = stringifyObjSafely(circularObj as any)
expect(output).toEqual('stringify error')
})
})
45 changes: 45 additions & 0 deletions packages/utils/lib/jsonUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Parses a JSON string safely and returns a JavaScript object.
* @param str - The JSON string to parse.
* @returns A JavaScript object if parsing is successful, otherwise void.
*/
export const parseJSONSafely = (str: any): Record<string, any> | void => {
try {
return JSON.parse(str)
} catch (error) {
console.error('An error occurred while parsing the JSON string')
}
}

/**
* Safely stringify a JavaScript object to a JSON string, handling circular references.
* @param obj - The object to stringify.
* @param tabSpaces - The number of spaces to use for indentation.
* @returns The JSON string representation of the object, or 'stringify error' if an error occurs.
*/
export const stringifyObjSafely = (obj: Record<string, any>, tabSpaces?: number): string => {
const cache = new Set()
try {
if (typeof obj === 'string') {
return obj
}
return JSON.stringify(
obj,
(_key, value) => {
if (typeof value === 'object' && value !== null) {
if (cache.has(value)) {
throw new Error('Circular reference detected')
}
cache.add(value)
}
return value
},
tabSpaces,
)
} catch (error) {
console.error(error)
return 'stringify error'
} finally {
cache.clear()
}
}

0 comments on commit 1377eea

Please sign in to comment.