Daarwin
Daarwin

Reputation: 3014

Sending HTML by Json

Im responding this to a Jquery Ajax call and it works well:

var jSonTestResultReport =@"{ ""html"" : ""I am text!"" }";

The Javascript receives it and takes the text and presents it in a Div, i can see it saying "I am Text".

But when i try to do this:

var jSonTestResultReport =@"{ ""html"" : ""<li style=""color:green;"">I am text</li>"" }";

i get the error of

unexpected token c.

How can send html by Json?

Upvotes: 3

Views: 8741

Answers (3)

L.B
L.B

Reputation: 116108

var jSonTestResultReport =@"{ ""html"" : ""<li style=""color:green;"">I am text</li>"" }";

will create a json string as

{ "html" : "<li style="color:green;">I am text</li>" }

which is not valid. unexpected token c. comes from the first letter of color.

Use a real json parser instead of forming json manually.

var json = JsonConvert.SerializeObject(new { html=@"<li style=""color:green;"">I am text</li>" });

PS: var jSonTestResultReport =@"{ ""html"" : "I am text!" }"; is not compilable.

Upvotes: 7

EaterOfCode
EaterOfCode

Reputation: 2222

escape your "" qoutes like \"" in the <li ... > otherwise JSON will die because its a text delimeter

var jSonTestResultReport =
     @"{ ""html"" : ""<li style=\""color:green;\"">I am text</li>"" }";

Upvotes: 1

HatSoft
HatSoft

Reputation: 11191

Why don't you use the jQuery.parseJSON method this is more clearer and readable then the way you are using with lots of double quotes

e.g.

var obj = jQuery.parseJSON('{"html": "<listyle='color: green;'>Iamtext</li>"}');

Also to speed things I would suggest you make use of JsonLint validator to validate your json object

Upvotes: 0

Related Questions