object-shape-tester
Version:
Test object properties and value types.
22 lines (21 loc) • 667 B
JavaScript
import { assertValidShape } from './verify-shape/verify-shape.js';
/**
* Parse a JSON string and verify it against the given shape definition.
*
* @category Main
* @example
*
* ```ts
* import {parseJsonWithShape, defineShape} from 'object-shape-tester';
*
* const result = parseJsonWithShape('{"a": "hello"}', defineShape({a: ''}));
* ```
*
* @throws If the parsed JSON does not match the shape definition or if the JSON parsing throws an
* error.
*/
export function parseJsonWithShape(json, shape, options = {}, failureMessage) {
const parsed = JSON.parse(json);
assertValidShape(parsed, shape, options, failureMessage);
return parsed;
}