diff --git a/lib/parse.js b/lib/parse.js index 84d142f..f1069a4 100644 --- a/lib/parse.js +++ b/lib/parse.js @@ -169,7 +169,7 @@ var json_parse = function (options) { at += 1; return ch; }, - number = function () { + number = function (schema) { // Parse a number value. var number, @@ -206,6 +206,10 @@ var json_parse = function (options) { error('Bad number'); } else { if (BigNumber == null) BigNumber = require('bignumber.js'); + if (schema === `bigint`) return _options.useNativeBigInt + ? BigInt(number) + : new BigNumber(number); + if (schema === `number`) return number; if (Number.isSafeInteger(number)) return !_options.alwaysParseAsBig ? number @@ -299,8 +303,10 @@ var json_parse = function (options) { error("Unexpected '" + ch + "'"); }, value, // Place holder for the value function. - array = function () { + array = function (schema) { // Parse an array value. + + if (!Array.isArray(schema)) schema = []; var array = []; @@ -311,8 +317,10 @@ var json_parse = function (options) { next(']'); return array; // empty array } + let i = 0; while (ch) { - array.push(value()); + array.push(value(schema[i])); + if (schema.length > 0 && i < schema.length) i++; white(); if (ch === ']') { next(']'); @@ -324,8 +332,10 @@ var json_parse = function (options) { } error('Bad array'); }, - object = function () { + object = function (schema) { // Parse an object value. + + if (typeof schema !== `object`) schema = {}; var key, object = Object.create(null); @@ -365,7 +375,7 @@ var json_parse = function (options) { object[key] = value(); } } else { - object[key] = value(); + object[key] = value(schema?.[key]); } white(); @@ -380,35 +390,35 @@ var json_parse = function (options) { error('Bad object'); }; - value = function () { + value = function (schema) { // Parse a JSON value. It could be an object, an array, a string, a number, // or a word. white(); switch (ch) { case '{': - return object(); + return object(schema); case '[': - return array(); + return array(schema); case '"': return string(); case '-': - return number(); + return number(schema); default: - return ch >= '0' && ch <= '9' ? number() : word(); + return ch >= '0' && ch <= '9' ? number(schema) : word(); } }; // Return the json_parse function. It will have access to all of the above // functions and variables. - return function (source, reviver) { + return function (source, reviver, schema) { var result; text = source + ''; at = 0; ch = ' '; - result = value(); + result = value(schema); white(); if (ch) { error('Syntax error');