Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 22 additions & 12 deletions lib/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ var json_parse = function (options) {
at += 1;
return ch;
},
number = function () {
number = function (schema) {
// Parse a number value.

var number,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 = [];

Expand All @@ -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(']');
Expand All @@ -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);
Expand Down Expand Up @@ -365,7 +375,7 @@ var json_parse = function (options) {
object[key] = value();
}
} else {
object[key] = value();
object[key] = value(schema?.[key]);
}

white();
Expand All @@ -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');
Expand Down