Skip to content
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 4 commits into from
May 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions docs/docs/utils/common/parseJson.md
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
```
16 changes: 16 additions & 0 deletions packages/utils/src/common/parseJson/index.ts
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}`);
Copy link
Contributor

@ssi02014 ssi02014 May 11, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

한국어로 작성되서 고민을 해봤는데요 modern-kit은 영어를 타겟으로 하지 않고 있어서 추후에 기존에 영어로 작성된 내용들을 한국어로 변환할지 고민이네요..!

ㅎㅎㅎ참고만해주시면 감사드립니다!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ssi02014 이전에 말씀해주셨던듯하여 일단 한글로 작성해두었는데 혹시 영어를 타겟으로 하려 하신다면 말씀주시면 언제든 수정하겠습니다!

return null;
}
};
62 changes: 62 additions & 0 deletions packages/utils/src/common/parseJson/parseJson.spec.ts
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();
});
});