tags:

views:

4911

answers:

3

I've generated some JSON and I'm trying to pull it into an object in javascript and I keep getting errors. Here's what I have:

var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = eval('('+data+')');

This gives me an error: unterminated string literal

When I take out the \n after sometext the error goes away. I can't seem to figure out why the \n makes eval fail.

+13  A: 

I guess this is what you want:

var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';

(You need to escape the "\" in your string, otherwise it will become a newline in the JSON source, not the JSON data.)

BlaM
+1  A: 

var data = '{"count" : 1, "stack" : "sometext\n\n"}';

+1  A: 

You might want to look into this C# function to escape the string:

http://www.aspcode.net/C-encode-a-string-for-JSON-JavaScript.aspx

public static string Enquote(string s)
{ if (s == null || s.Length == 0)
{ return "\"\""; } char c; int i; int len = s.Length; StringBuilder sb = new StringBuilder(len + 4); string t;

sb.Append('"'); 
for (i = 0; i < len; i += 1)  
{ 
    c = s[i]; 
    if ((c == '\\') || (c == '"') || (c == '>')) 
    { 
        sb.Append('\\'); 
        sb.Append(c); 
    } 
    else if (c == '\b') 
        sb.Append("\\b"); 
    else if (c == '\t') 
        sb.Append("\\t"); 
    else if (c == '\n') 
        sb.Append("\\n"); 
    else if (c == '\f') 
        sb.Append("\\f"); 
    else if (c == '\r') 
        sb.Append("\\r"); 
    else 
    { 
        if (c < ' ')  
        { 
            //t = "000" + Integer.toHexString(c); 
            string tmp = new string(c,1); 
            t = "000" + int.Parse(tmp,System.Globalization.NumberStyles.HexNumber); 
            sb.Append("\\u" + t.Substring(t.Length - 4)); 
        }  
        else  
        { 
            sb.Append(c); 
        } 
    } 
} 
sb.Append('"'); 
return sb.ToString();

}

Ronnie