$ gnpm install parse-json-object
Parse a typed JSON object.
If I should maintain this repo, please ⭐️
DM me on Twitter if you have questions or suggestions.
undefined
if unable to parseyarn add parse-json-object
npm install parse-json-object
pnpm add parse-json-object
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 to validate more complex types:
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:
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
Copyright 2013 - present © cnpmjs.org | Home |