Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Jun 2010
    Posts
    278
    Thanks
    63
    Thanked 8 Times in 8 Posts

    How to get JSON to convert newlines correctly?

    Consider the following user input via a textarea:

    a
    b
    c


    This contains the following bytes:

    0x61 0x0A 0x62 0x0A 0x62

    BUT, when I run this string through JSON.stringigy, I find that the newline characters (0x0A) have been replaced by their unicode equivalent, which is \u000a

    My server-side script uses utf-8 encoding, so of course it doesn't convert \u000a back to 0x0A correctly.

    How can I force JSON to encode newlines (and other backslash-escaped characters) using utf-8, rather than unicode?

    I currently have a hack in my server-side script to do the conversion, but I'm not happy about that!

  • #2
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,184
    Thanks
    10
    Thanked 569 Times in 550 Posts
    my browser's JSON.stringify() uses "\n" for new lines. your problem might be something else. one major suspect: a different character encoding on one of the requests/response than another one. another suspect is the automatic conversion of "\r\n" to "\n" by browser textareas on window's machines.

    your server might very well attempt to apply its own remedies to either of those behaviors, compounding the problem.

    hand-polishing JSON on the backend is fairly common. Test in IE, Mobile, and Chrome, and if whatever voodoo you have going works, don't sweat the small stuff...
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •