Omar Olivo
Omar Olivo

Reputation: 45

How to parse HTML string using JSON.parse() in JavaScript?

I have an ASP.NET MVC application returning a JSON string to the VIEW.

// Parsing the model returned on the VIEW
var jsonString = '@Html.Raw(Model.ToJson())';
var jsonObj = JSON.parse(jsonString);

The problem is that I am not able to parse because the jsonString contains characters such as "\" and "'".

//Sample string
{ "description" : "<p>Sample<span style=\"color: #ff6600;\"> Text</span></strong></p>" }

Upvotes: 3

Views: 12590

Answers (3)

Stoyan Bukovich
Stoyan Bukovich

Reputation: 87

There you go:

using Newtonsoft.Json;

JsonConvert.SerializeObject(your html string here);

Upvotes: 0

cmbuckley
cmbuckley

Reputation: 42458

JSON is valid JavaScript, so you can just do this:

var jsonObj = @Html.Raw(Model.ToJson());

FYI, the reason the JSON parsing is failing is because the although the " are escaped with \ to make it valid JSON, the backslashes themselves need escaping in the string for them to be seen by the JSON parser. Compare:

JSON.parse('"quote: \""');  // error: unexpected string
JSON.parse('"quote: \\""'); // 'quote: "'

This example should also clarify what's happening to the backslashes:

var unescaped = '\"', escaped = '\\"';

console.log(unescaped, unescaped.length); // '"',  1
console.log(escaped, escaped.length);     // '\"', 2

Upvotes: 5

Guffa
Guffa

Reputation: 700212

If you want to create a valid Javascript string, you need to escape backslashes and apostrophes:

var jsonString = '@Html.Raw(Model.ToJson().Replace("\\", "\\\\").Replace("'", "\\'"))';

Upvotes: 0

Related Questions