Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript extract json from string

function extractJSON(str) {
    var firstOpen, firstClose, candidate;
    firstOpen = str.indexOf('{', firstOpen + 1);
    do {
        firstClose = str.lastIndexOf('}');
        console.log('firstOpen: ' + firstOpen, 'firstClose: ' + firstClose);
        if(firstClose <= firstOpen) {
            return null;
        }
        do {
            candidate = str.substring(firstOpen, firstClose + 1);
            console.log('candidate: ' + candidate);
            try {
                var res = JSON.parse(candidate);
                console.log('...found');
                return [res, firstOpen, firstClose + 1];
            }
            catch(e) {
                console.log('...failed');
            }
            firstClose = str.substr(0, firstClose).lastIndexOf('}');
        } while(firstClose > firstOpen);
        firstOpen = str.indexOf('{', firstOpen + 1);
    } while(firstOpen != -1);
}

var obj = {'foo': 'bar', xxx: '} me[ow]'};
var str = 'blah blah { not {json but here is json: ' + JSON.stringify(obj) + ' and here we have stuff that is } really } not ] json }} at all';
var result = extractJSON(str);
console.log('extracted object:', result[0]);
console.log('expected object :', obj);
console.log('did it work     ?', JSON.stringify(result[0]) == JSON.stringify(obj) ? 'yes!' : 'no');
console.log('surrounding str :', str.substr(0, result[1]) + '<JSON>' + str.substr(result[2]));
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript round down to 2 decimal places 
Javascript :: use params in Class based component 
Javascript :: random email js 
Javascript :: javascript push 
Javascript :: delay sleep 
Javascript :: react hooks example 
Javascript :: play audio file in phaser 
Javascript :: simultaneos mouse buttons clicked js 
Javascript :: stop jboss from cli 
Javascript :: how to check alphabet case in javascript 
Javascript :: str_limit function filter vuejs 
Javascript :: display:flex 
Javascript :: loading screen html css js 
Javascript :: mongodb find array with element 
Javascript :: crontab validate regex 
Javascript :: compare string length javascript 
Javascript :: js hide element 
Javascript :: basic react code 
Javascript :: chaine de caractère dans une autres js 
Javascript :: div diseaper going down 
Javascript :: testing jest 
Javascript :: react show view based on role permission 
Javascript :: launch json for golang with args 
Javascript :: Remove an item from the beginning of an Array 
Javascript :: ng-lazyload-image 
Javascript :: javascript make title blink 
Javascript :: remove array value by index js 
Javascript :: Century From Year 
Javascript :: escape double quotes in json 
Javascript :: vscode jest disable auto run 
ADD CONTENT
Topic
Content
Source link
Name
6+4 =