views:

190

answers:

1

I need to eval an JavaScriptSerializer() object.

var userSettings = '<%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewData["UserSettings"]) %>';

The above line gives the output as:

{"SalesTaxPercentage":7.75,"StartOfWeek":"SUNDAY","NoofRowsInList":10,"ShowDashboardEntry":5,"DisplayContactsFormat":"LastName, FirstName","FooterNotes":""When you look good, you feel good...when you feel good, your attitude changes...and attitude is everything!"

You are the heart of my business....THANK YOU!"}

When i use eval for the serialized content like:

userSettings = eval("(" + userSettings + ")"); 

It throws an error:

missing } after property list

This is because of the special characters in the serialized object (in FooterNotes with " and some other characters in between start and end quotes) during eval.

How can i remove the special characters in serialized before eval?

Or how can i get the value of SalesTaxPercentage from searialized object?

A: 

I think you can simply remove single quotes in the first string and don't use eval (userSettings will be already an object).

Another way is to double backslashes so your string will stay quoted, something like this (not tested):

var userSettings = '<%= System.Text.RegularExpressions.Regex.Replace(
    new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewData["UserSettings"]), @"\134", "\\$0"); %>';
meze
The problem is i need to get the value of "SalesTaxPercentage", which i was not able to get without eval. If i use eval, i can get that value simply by accessing "userSettings.SalesTaxPercentage"
Prasad
I meant you could write `var userSettings = <%= new System.Web.Script.Serialization... %>;` and then you could get that value by "userSettings.SalesTaxPercentage". No need to use eval in that case: "Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss."
meze