javascript extract json from string

Solutions on MaxInterview for javascript extract json from string by the best coders in the world

showing results for - "javascript extract json from string"
Jan
15 Apr 2020
1function extractJSON(str) {
2    var firstOpen, firstClose, candidate;
3    firstOpen = str.indexOf('{', firstOpen + 1);
4    do {
5        firstClose = str.lastIndexOf('}');
6        console.log('firstOpen: ' + firstOpen, 'firstClose: ' + firstClose);
7        if(firstClose <= firstOpen) {
8            return null;
9        }
10        do {
11            candidate = str.substring(firstOpen, firstClose + 1);
12            console.log('candidate: ' + candidate);
13            try {
14                var res = JSON.parse(candidate);
15                console.log('...found');
16                return [res, firstOpen, firstClose + 1];
17            }
18            catch(e) {
19                console.log('...failed');
20            }
21            firstClose = str.substr(0, firstClose).lastIndexOf('}');
22        } while(firstClose > firstOpen);
23        firstOpen = str.indexOf('{', firstOpen + 1);
24    } while(firstOpen != -1);
25}
26
27var obj = {'foo': 'bar', xxx: '} me[ow]'};
28var str = 'blah blah { not {json but here is json: ' + JSON.stringify(obj) + ' and here we have stuff that is } really } not ] json }} at all';
29var result = extractJSON(str);
30console.log('extracted object:', result[0]);
31console.log('expected object :', obj);
32console.log('did it work     ?', JSON.stringify(result[0]) == JSON.stringify(obj) ? 'yes!' : 'no');
33console.log('surrounding str :', str.substr(0, result[1]) + '<JSON>' + str.substr(result[2]));
34