https://github.com/bconnorwhite/parse-json-object
Parse a typed JSON object
https://github.com/bconnorwhite/parse-json-object
json node nodejs parse typescript
Last synced: 11 months ago
JSON representation
Parse a typed JSON object
- Host: GitHub
- URL: https://github.com/bconnorwhite/parse-json-object
- Owner: bconnorwhite
- Created: 2020-08-16T03:23:55.000Z (almost 6 years ago)
- Default Branch: main
- Last Pushed: 2023-01-29T23:58:28.000Z (over 3 years ago)
- Last Synced: 2024-11-05T02:04:00.536Z (over 1 year ago)
- Topics: json, node, nodejs, parse, typescript
- Language: TypeScript
- Homepage:
- Size: 359 KB
- Stars: 3
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
Awesome Lists containing this project
README
Parse a typed JSON object.
_If I should maintain this repo, please ⭐️_
_DM me on [Twitter](https://twitter.com/bconnorwhite) if you have questions or suggestions._
---
- Returns `undefined` if unable to parse
- Returns value if successful
## Installation
```sh
yarn add parse-json-object
```
```sh
npm install parse-json-object
```
```sh
pnpm add parse-json-object
```
## Usage
### Types
```ts
import {
parseJSONValue,
parseJSONObject,
parseJSONArray,
parseString
} from "parse-json-object";
parseJSONValue("1"); // 1
parseJSONValue("not valid json"); // undefined
parseJSONObject('{"a": 1}'); // { a: 1 }
parseJSONArray("[1, 2, 3]"); // [1, 2, 3]
parseString('"hello"'); // "hello"
```
Additionally, a `parse` function is provided, which takes a function to validate the parsed value. This can be easily used with [zod](https://github.com/colinhacks/zod) to validate more complex types:
```ts
import { parse } from "parse-json-object";
import z from "zod";
const schema = z.object({
a: z.number(),
b: z.string()
});
parse('{ a: 1, b: "hello" }', schema); // { a: 1, b: 'hello' }
```
A custom typeguard can also be used:
```ts
import { parse } from "parse-json-object";
function isNumber(value: unknown): value is number {
return typeof value === "number";
}
parse("1", isNumber); // 1
parse("not a number", isNumber); // undefined
```
Dependencies
- [is-zod](https://www.npmjs.com/package/is-zod): Typeguard to check if a value matches a zod schema
- [types-json](https://www.npmjs.com/package/types-json): Type checking for JSON values
Dev Dependencies
- [autorepo](https://www.npmjs.com/package/autorepo): Autorepo abstracts away your dev dependencies, providing a single command to run all of your scripts.
- [zod](https://www.npmjs.com/package/zod): TypeScript-first schema declaration and validation library with static type inference
License
[MIT](https://opensource.org/licenses/MIT)
## Related Packages:
- [stringify-json-object](https://www.npmjs.com/package/stringify-json-object): Stringify and format a JSON object
- [types-json](https://www.npmjs.com/package/types-json): Type checking for JSON objects