(text: string, errors: ParseError[] = [], options: ParseOptions = ParseOptions.DEFAULT)
| 844 | * Therefore always check the errors list to find out if the input was valid. |
| 845 | */ |
| 846 | export function parse(text: string, errors: ParseError[] = [], options: ParseOptions = ParseOptions.DEFAULT): any { |
| 847 | let currentProperty: string | null = null; |
| 848 | let currentParent: any = []; |
| 849 | const previousParents: any[] = []; |
| 850 | |
| 851 | function onValue(value: unknown) { |
| 852 | if (Array.isArray(currentParent)) { |
| 853 | currentParent.push(value); |
| 854 | } else if (currentProperty !== null) { |
| 855 | currentParent[currentProperty] = value; |
| 856 | } |
| 857 | } |
| 858 | |
| 859 | const visitor: JSONVisitor = { |
| 860 | onObjectBegin: () => { |
| 861 | const object = {}; |
| 862 | onValue(object); |
| 863 | previousParents.push(currentParent); |
| 864 | currentParent = object; |
| 865 | currentProperty = null; |
| 866 | }, |
| 867 | onObjectProperty: (name: string) => { |
| 868 | currentProperty = name; |
| 869 | }, |
| 870 | onObjectEnd: () => { |
| 871 | currentParent = previousParents.pop(); |
| 872 | }, |
| 873 | onArrayBegin: () => { |
| 874 | const array: any[] = []; |
| 875 | onValue(array); |
| 876 | previousParents.push(currentParent); |
| 877 | currentParent = array; |
| 878 | currentProperty = null; |
| 879 | }, |
| 880 | onArrayEnd: () => { |
| 881 | currentParent = previousParents.pop(); |
| 882 | }, |
| 883 | onLiteralValue: onValue, |
| 884 | onError: (error: ParseErrorCode, offset: number, length: number) => { |
| 885 | errors.push({ error, offset, length }); |
| 886 | } |
| 887 | }; |
| 888 | visit(text, visitor, options); |
| 889 | return currentParent[0]; |
| 890 | } |
| 891 | |
| 892 | |
| 893 | /** |
searching dependent graphs…