JSON
SafeJSON
parse
import { SafeJSON } from 'funkcia/json';
// ┌─── Result<unknown, SyntaxError>
// â–¼
const goodJson = SafeJSON.parse('{ "name": "John" }');
// Output: Ok({ name: "John" })
const invalidJson = SafeJSON.parse('{ "name": John }');
// Output: Error(SyntaxError: Unexpected token 'J', "{ "name": John }" is not valid JSON)stringify
import { SafeJSON } from 'funkcia/json';
// With function replacer
// ┌─── Result<string, TypeError>
// â–¼
const result = SafeJSON.stringify(
{ name: "John", age: 30 },
(key, value) => typeof value === 'number' ? value.toString() : value,
2
);
// Output: Ok('{\n "name": "John",\n "age": "30"\n}')
// With array replacer
// ┌─── Result<string, TypeError>
// â–¼
const result = SafeJSON.stringify(
{ name: "John", age: 30, email: "[email protected]" },
['name', 'age'],
2
);
// Output: Ok('{\n "name": "John",\n "age": 30\n}')Last updated
Was this helpful?