Skip to content
This repository has been archived by the owner on Sep 2, 2022. It is now read-only.

Commit

Permalink
Implement json validation util
Browse files Browse the repository at this point in the history
  • Loading branch information
Ray Foo authored and busyxiang committed Aug 26, 2022
1 parent b44f17d commit 5cad671
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/olive-ghosts-chew.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@busyxiang/utilities-js': patch
---

Add validation for Json
15 changes: 15 additions & 0 deletions src/json.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { isValidJson } from './json';

describe('isValidJson', () => {
test('it should return true if JSON is valid', () => {
const isValid = isValidJson(JSON.stringify({ x: 1 }));

expect(isValid).toBe(true);
});

test('it should return false if JSON is not valid', () => {
const isValid = isValidJson('invalid json');

expect(isValid).toBe(false);
});
});
8 changes: 8 additions & 0 deletions src/json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export const isValidJson = (str: string) => {
try {
JSON.parse(str);
return true;
} catch (error) {
return false;
}
};

0 comments on commit 5cad671

Please sign in to comment.