views:

792

answers:

4

Hi,

My JSON request seems to be failing because of line breaks (I am programatically weaving my own JSON string).

How can I escape for line breaks?

{"rc": "200", "m" : "", "o": "<div class='s1'>
            <div class='avatar'>                    
                <a href='\/asdf'>asdf<\/a><br \/>
                <strong>0<\/strong>
            <\/div>
            <div class='sl'>
                <p>
                    444444444
                <\/p>
            <\/div>
            <div class='clear'>
            <\/div>                        
        <\/div>"}

string jsonString = BuildJSON(someCollection).Replace(@"/", @"\/");

A: 

Before you build that string do a replace with \n.

Daniel A. White
replace what with \n?
mrblah
newline characters are \n in JavaScript. You need to check your file to see what http://en.wikipedia.org/wiki/Newline 's are being used, and replace them. So it ends up as: {"rc": "200", "m" : "", "o": "<div class='s1'>\n <div class='avatar'> \n <a href='\/asdf'>asdf<\/a><br \/>\n <strong>0<\/strong>\n <\/div>\n <div class='sl'>\n <p>\n 444444444\n <\/p>\n <\/div>\n <div class='clear'>\n <\/div> \n <\/div>"}
artlung
A: 

I think you might be causing yourself a problem in your example... you don't need to escape the / character, just any \ characters. So \/ is actually wrong and it should just be /.

Any instances of \ should be changed to \.

Try it with this amendment.

Example of stripping out line breaks can be found here:

http://www.bennadel.com/blog/161-Ask-Ben-Javascript-Replace-And-Multiple-Lines-Line-Breaks.htm

Sohnee
A: 

You should be able to escape the line breaks by calling .Replace("\n","\n").

Sean Lynch
A: 

You should not need to serialize JSON on your own. Use .NET to do it for you:

JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();

string JSON = jsonSerializer.Serialize(new {
    rc = 200,
    m = "",
    o = "<div>...</div>" });

The full namespace name of the serializer is: System.Web.Script.Serialization.JavaScriptSerializer.

Jan Zich