in src/impl/parser.ts [162:206]
export function parse(text: string, errors: ParseError[] = [], options: ParseOptions = ParseOptions.DEFAULT): any {
let currentProperty: string | null = null;
let currentParent: any = [];
const previousParents: any[] = [];
function onValue(value: any) {
if (Array.isArray(currentParent)) {
(<any[]>currentParent).push(value);
} else if (currentProperty !== null) {
currentParent[currentProperty] = value;
}
}
const visitor: JSONVisitor = {
onObjectBegin: () => {
const object = {};
onValue(object);
previousParents.push(currentParent);
currentParent = object;
currentProperty = null;
},
onObjectProperty: (name: string) => {
currentProperty = name;
},
onObjectEnd: () => {
currentParent = previousParents.pop();
},
onArrayBegin: () => {
const array: any[] = [];
onValue(array);
previousParents.push(currentParent);
currentParent = array;
currentProperty = null;
},
onArrayEnd: () => {
currentParent = previousParents.pop();
},
onLiteralValue: onValue,
onError: (error: ParseErrorCode, offset: number, length: number) => {
errors.push({ error, offset, length });
}
};
visit(text, visitor, options);
return currentParent[0];
}