-
Notifications
You must be signed in to change notification settings - Fork 13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(utils): parseJson 함수 추가 완료 #115
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
b86f90e
feat(utils): parseJson 함수 추가 완료
Sangminnn e0eed83
imp(utils): parseJson의 입력값이 빈 문자열인 경우에도 그대로 반환하도록 수정 및 일부 타입 보강 완료
Sangminnn 179d6b2
imp(utils): parseJson함수 내 조건식 위치 변경 및 환경변수 체크구문 제거 완료
Sangminnn 7948adc
docs(utils): parseJson함수 문서 타입 반환값 수정 완료
Sangminnn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
# parseJson | ||
|
||
일반적으로 JSON.parse를 사용하는 경우 일부 input값(ex. 빈 문자열, undefined, NaN)에 대해서는 에러를 반환합니다. 이 함수를 사용하면 에러를 반환하는 값에 대해서는 null을 반환하여 파싱 시의 예상치 못한 에러를 방지할 수 있습니다. | ||
|
||
<br /> | ||
|
||
## Interface | ||
```tsx | ||
const parseJson: <T>(value: any) => T | null | ||
``` | ||
|
||
## Usage | ||
```ts | ||
import { parseJson } from '@modern-kit/utils'; | ||
|
||
type NormalObject = { a: 1, b: 2 } | ||
|
||
const normalObject = parseJSON<NormalObject>(`{ "a": 1, "b": 2 }`); // { a: 1, b: 2 } | null | ||
const emptyString = parseJSON<''>(''); // '' | null | ||
const nullValue = parseJSON<null>(null); // null | ||
const undefinedValue = parseJSON<undefined>(undefined); // undefined | null | ||
const NaNValue = parseJSON<typeof NaN>(NaN); // number | null | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
export const parseJSON = <T>(value: any): T | null => { | ||
if (typeof value !== 'string') { | ||
return value as T; | ||
} | ||
|
||
if (value === '') { | ||
return '' as T; | ||
} | ||
|
||
try { | ||
return JSON.parse(value) as T; | ||
} catch { | ||
console.error(`데이터를 파싱하는 데에 실패했습니다. 원본: ${value}`); | ||
return null; | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
import { parseJSON } from '.'; | ||
|
||
type Test1 = { a: 1; b: 2 }; | ||
type Test2 = { | ||
a: 1; | ||
b: [2, 3, { c: 4 }]; | ||
d: { e: 5; f: 6 }; | ||
}; | ||
type Test3 = ['foo', { bar: 'baz' }]; | ||
|
||
describe('parseJSON', () => { | ||
it('should return original value for falsy value', () => { | ||
const falseValue = parseJSON<false>(false); | ||
const zeroNumberValue = parseJSON<0>(0); | ||
const emptyStringValue = parseJSON<''>(''); | ||
const nullValue = parseJSON<null>(null); | ||
const undefinedValue = parseJSON<undefined>(undefined); | ||
const NaNValue = parseJSON<typeof NaN>(NaN); | ||
|
||
expect(falseValue).toBe(false); | ||
expect(zeroNumberValue).toBe(0); | ||
expect(emptyStringValue).toBe(''); | ||
expect(nullValue).toBeNull(); | ||
expect(undefinedValue).toBeUndefined(); | ||
expect(NaNValue).toBeNaN(); | ||
}); | ||
|
||
it('should correctly parse stringified value', () => { | ||
const result = parseJSON<Test1>(`{ "a": 1, "b": 2 }`); | ||
|
||
expect(result).toEqual({ a: 1, b: 2 }); | ||
}); | ||
|
||
it('should correctly parse complex JSON objects', () => { | ||
const complexJson = `{ | ||
"a": 1, | ||
"b": [2, 3, {"c": 4}], | ||
"d": {"e": 5, "f": 6} | ||
}`; | ||
const result = parseJSON<Test2>(complexJson); | ||
|
||
expect(result).toEqual({ | ||
a: 1, | ||
b: [2, 3, { c: 4 }], | ||
d: { e: 5, f: 6 }, | ||
}); | ||
}); | ||
|
||
it('should correctly parse JSON arrays', () => { | ||
const jsonArray = `["foo", {"bar": "baz"}]`; | ||
const result = parseJSON<Test3>(jsonArray); | ||
|
||
expect(result).toEqual(['foo', { bar: 'baz' }]); | ||
}); | ||
|
||
it('should return null for incorrect JSON format', () => { | ||
const incorrectJson = `{a: 1, b: 2}`; | ||
const result = parseJSON<null>(incorrectJson); | ||
|
||
expect(result).toBeNull(); | ||
}); | ||
}); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
한국어로 작성되서 고민을 해봤는데요 modern-kit은 영어를 타겟으로 하지 않고 있어서 추후에 기존에 영어로 작성된 내용들을 한국어로 변환할지 고민이네요..!
ㅎㅎㅎ참고만해주시면 감사드립니다!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ssi02014 이전에 말씀해주셨던듯하여 일단 한글로 작성해두었는데 혹시 영어를 타겟으로 하려 하신다면 말씀주시면 언제든 수정하겠습니다!