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.

Warning

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

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

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.