instance method String#evalJSON

View source on GitHub →

String#evalJSON([sanitize = false]) → object

Evaluates the JSON in the string and returns the resulting object.

If the optional sanitize parameter is set to true, the string is checked for possible malicious attempts; if one is detected, eval is not called.


If the JSON string is not well formated or if a malicious attempt is detected a SyntaxError is thrown.

var person = '{ "name": "Violet", "occupation": "character" }'.evalJSON();;
//-> "Violet"
 person = 'grabUserPassword()'.evalJSON(true);
//-> SyntaxError: Badly formed JSON string: 'grabUserPassword()'
 person = '/*-secure-\n{"name": "Violet", "occupation": "character"}\n*\/'.evalJSON();
//-> "Violet"

Always set the sanitize parameter to true for data coming from externals sources to prevent XSS attacks.

As String#evalJSON internally calls String#unfilterJSON, optional security comment delimiters (defined in Prototype.JSONFilter) are automatically removed.