Reputation: 154
I hit a problem with JSON. I want to pass serialized object to a JSON.parse method in JS. Everything works fine until one of string values does not have quotes, like for example HTML code. Then you get JSON parse error in JS.
Simply I get:
var test = JSON.parse('{"test":"<p>Terms <a href=\"google.pl\"></a></p>"}');
But what works is:
var test = JSON.parse('{"test":"<p>Terms <a href=\\"google.pl\\"></a></p>"}');
Here is my test view code, any thoughts? How to pass this object properly?
@{
Layout = null;
}
@{
string args = Newtonsoft.Json.JsonConvert.SerializeObject(new
{
test = @"<p>Terms <a href=""google.pl""></a></p>"
}, new Newtonsoft.Json.JsonSerializerSettings
{
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),
});
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<script>
var test = JSON.parse('@Html.Raw(args)');
</script>
<div>
</div>
</body>
</html>
Upvotes: 2
Views: 1825
Reputation: 1499
You don't need to parse it, as it is already a JSON object. Just use:
<script>
var test = @Html.Raw(args);
</script>
JSON.parse
is used to parse string to object.
Upvotes: 4