Tip: Relaxing JSON strictness

I’ve decided to start posting about the little things I encounter day by day. Post #1: I needed less strict JSON parsing than Firefox usually does and a little RegEx seems to do the trick for now (it also allows for single word strings à la PHP, e.g. FOO becomes “FOO”:

var findRelevantToken=/(?:"(?:|.*?[^\\](?:\\\\)*)"|([\s,\:\{\[]|^)([a-z\_\$][a-z\_\$0-9]*))/gi;
   str=str.replace(findRelevantToken,function(m,ssep,nqs){
   if(nqs) return ssep+'"'+nqs+'"';
   else return m;
});

Leave a Reply

Your email address will not be published. Required fields are marked *


*