-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjson.ts
More file actions
25 lines (21 loc) · 764 Bytes
/
json.ts
File metadata and controls
25 lines (21 loc) · 764 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { cleanJSON } from './string';
export function parse(str) {
if (str === 'null') return undefined;
// Extract the JSON part from the str using a regex that matches the JSON structure
const jsonMatch = str.match(/(\[|\{)[^]*(\]|\})/);
if (!jsonMatch) {
// console.error('No valid JSON found')
return undefined;
}
const jsonString = jsonMatch[0].replace(/\bundefined\b/g, 'null');
// Remove single-line and multi-line comments using regex
const cleanedResponse = jsonString.replace(/\/\/.*|\/\*[^]*?\*\//g, '');
// Parse the cleaned JSON string
try {
const json = JSON.parse(cleanedResponse);
return json;
} catch (error) {
console.error('Error parsing JSON:', error, cleanedResponse);
return undefined;
}
}