How do I handle newlines in JSON?

后端 未结 10 1316
后悔当初
后悔当初 2020-11-22 05:28

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

var data = \'{\"count\" : 1, \         


        
相关标签:
10条回答
  • 2020-11-22 05:51

    You will need to have a function which replaces \n to \\n in case data is not a string literal.

    function jsonEscape(str)  {
        return str.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r").replace(/\t/g, "\\\\t");
    }
    
    var data = '{"count" : 1, "stack" : "sometext\n\n"}';
    var dataObj = JSON.parse(jsonEscape(data));
    

    Resulting dataObj will be

    Object {count: 1, stack: "sometext\n\n"}
    
    0 讨论(0)
  • 2020-11-22 05:53

    I guess this is what you want:

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

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

    0 讨论(0)
  • 2020-11-22 05:53

    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 t = 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(); 
    } 
    
    0 讨论(0)
  • 2020-11-22 05:54

    well, it is not really necessary to create a function for this when it can be done simply with 1 CSS class.

    just wrap your text around this class and see the magic :D

     <p style={{whiteSpace: 'pre-line'}}>my json text goes here \n\n</p>
    

    note: because you will always present your text in frontend with HTML you can add the style={{whiteSpace: 'pre-line'}} to any tag, not just the p tag.

    0 讨论(0)
  • 2020-11-22 06:02

    JSON.stringify

    JSON.stringify(`{ 
      a:"a"
    }`)
    

    would convert the above string to

    "{ \n      a:\"a\"\n    }"
    

    as mentioned here

    json stringify

    This function adds double quotes at the beginning and end of the input string and escapes special JSON characters. In particular, a newline is replaced by the \n character, a tab is replaced by the \t character, a backslash is replaced by two backslashes \, and a backslash is placed before each quotation mark.

    0 讨论(0)
  • 2020-11-22 06:04

    As I understand you question, it is not about parsing JSON because you can copy-paste your JSON into your code directly - so if this is the case then just copy your JSON direct to dataObj variable without wrapping it with single quotes (tip: eval==evil)

    var dataObj = {"count" : 1, "stack" : "sometext\n\n"};
    
    console.log(dataObj);

    0 讨论(0)
提交回复
热议问题