DEV Community

Sandeep kamboj
Sandeep kamboj

Posted on

Parse JSON string without JSON.parse and eval()

    var jsonStr="{name:'abc',age:20}";
    var jsonObject = (new Function( "return " + jsonStr ) )() ;

Enter fullscreen mode Exit fullscreen mode

Top comments (4)

fnh profile image
Fabian Holzer

JSON.parse would yield a syntax error in this example, because jsonStr is not acutally JSON, since JSON requires double quotes for string, and requires the keys to be in string form as well.

But what is much more grave, this function is prone to script injection.

let jsonObject = 
  (letsHopeItsJson) => ((new Function( "return " + letsHopeItsJson) )())

let iffe = "(function(){alert('script injection')})()";



sandeepkamboj12 profile image
Sandeep kamboj

yes. this code is also used for script injection.

I have checked jquery parseJSON method in jquery library in 1.x version. It also uses this technique to parse json..

fnh profile image
Fabian Holzer • Edited

Just to be perfectly clear: script injection is not a feature, it is a security vurnerabilty. And that jQuery, in an apparently rather old version, did this in its days, is no excuse to repeat the mistake in 2018.

Thread Thread
glauberfunez profile image
Glauber Funez

right and what would be the best way to do that since JSON.parse doesn't work because it has a function?
I ask that because I have a very similar scenario.