Hello and welcome to our community! Is this your first visit?
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
    Thanked 8 Times in 8 Posts

    How to get JSON to convert newlines correctly?

    Consider the following user input via a textarea:


    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. #2
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Thanked 626 Times in 605 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...
    Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com


Posting Permissions

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