Controller parse json string in view

My MVC controller contains a collection that I want to pass to the view, so I:

// myCollection is a list of objects var j = new JavaScriptSerializer(); ViewBag.Data = j.Serialize(myCollection); 

And the look inside JS

 var data = $.parseJSON('@Html.Raw(ViewBag.Data)'); 

.. which expands to look something like this:

 var data = $.parseJSON('[{"Value":2,"Fullname":"Value"}]'); 

This works fine, but if my Json string contains a double quote, it gets the backslash escape code, and parseJson fails, for example:

 $.parseJSON('[{"Value":2,"Fullname":"Value \" with double quote"}]'); 

How to fix it?

+4
source share
2 answers

While the following JSON is true, it does not stay the same when the string is in JavaScript, as it will be undone first:

  '[{"Value":2,"Fullname":"Value \" with double quote"}]' 

JavaScript will disable this first to become:

  '[{"Value":2,"Fullname":"Value " with double quote"}]' 

When JSON arrives, it clearly sees an unexpected character, since the quote is now looking for the end of the line. What you need to do is double quote ( \\" works), anyway, whether you want to do this at the end of JS or .NET is probably completely up to you.

However, there really is no need to parse this with JSON at all, and you can just use it as an object literal like this:

 var data = @Html.Raw(ViewBag.Data); 

which translates to:

 var data = [{"Value":2,"Fullname":"Value \" with double quote"}]; 

.. which is absolutely true.

+1
source

why not just create a custom function and call parseJSON inside it. but replace \ "before that?

 function parseJson(str){ var temp = str.replace('\"', '"'); return $.parseJSON(temp); } 
-2
source

All Articles