7

I'm getting the following string:

var str='{"message":"hello\nworld"}';

I need to turn it into JSON object. However, I get an exception when I try JSON.parse(str) because of the \n

I saw this question but it did not help.

From that, I tried var j=JSON.parse(JSON.stringify(str))

But I'm still getting string instead of object when i use typeof j

I know using \\n works, but the thing is, it does not print on new line when i need to use the value.

UPDATE: OK, i just realized \\n is working. I'm using this to convert \n to \\n:

var str='{"message":"hello\nworld"}';
str=str.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r").replace(/\t/g, "\\\\t");

var json=JSON.parse(str);

console.log(json.message);

Can someone please correct it?

Community
  • 1
  • 1
Dushyant Bangal
  • 6,048
  • 8
  • 48
  • 80
  • Why not use `
    ` tag?
    – Pawan Nogariya Jun 14 '16 at 11:41
  • 3
    _"I know using `\\n` works, but the thing is, it does not print on new line when i need to use the value."_ This is the part you need to fix - `\\n` is correct here, assuming that you want `"message"` to contain a new line, as new lines themselves are not valid in JSON. – James Thorpe Jun 14 '16 at 11:42
  • 1
    @PawanNogariya its a string, I'm not forming html tags using it. I'm getting the data at my webservice. – Dushyant Bangal Jun 14 '16 at 11:44
  • @JamesThorpe, console.log(j.message) does not print it on new line – Dushyant Bangal Jun 14 '16 at 11:46
  • I does print it in a new line in cosole, see this fiddle https://jsfiddle.net/s8d8k3on/ – Pawan Nogariya Jun 14 '16 at 11:49
  • @DushyantBangal The code present in your question results in `j.message` being `undefined`. – James Thorpe Jun 14 '16 at 11:52
  • @JamesThorpe, yes, if i stringify it and then parse, it still returns string and not object. dont know why. Please see the update. – Dushyant Bangal Jun 14 '16 at 11:59
  • I think with your update you're just making your situation worse. What if your string genuinely needs a newline or tab in it (if it's prettified JSON for example) - you now can't do that and will get different errors. Can you alter the original output JSON to output `\\n` in the first place - as I mentioned earlier, newlines in JSON values are not valid in the first place, so whatever is providing you with that JSON output is simply not correct. Once you've fixed that, move on to your other issue of getting that newline to display correctly wherever it is that you're having _that_ problem. – James Thorpe Jun 14 '16 at 12:01
  • Here's the situation: An arduino device (which runs C) is sending it to me via a USB port. Sure, I dont feel it right to ask C to use `\\n` instead of `\n`. Dont want to bother the guy who will code Arduino. – Dushyant Bangal Jun 14 '16 at 12:05
  • You absolutely should ask them. The JSON string it's outputting currently contains a newline, rather than a marker that the _value within that string_ should contain a newline. This is the same whether the source of that is C or JavaScript or VB or SQL and is simply not valid. Anything you do is just glossing over that, and has the potential to introduce other errors. – James Thorpe Jun 14 '16 at 12:07

1 Answers1

13

Escaping \n to \\n was the right thing to do. In your code, the replace call was done wrong. You need fewer slashes. Updated your code :

var str='{"message":"hello\nworld"}';
str=str.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");

var json=JSON.parse(str); //No errors due to escaping

Now print it and you'll see the text being split into different lines.

console.log(json.message);
EnKrypt
  • 777
  • 8
  • 23
  • its a string, I'm not forming html tags using it. I'm getting the data at my webservice. I need to store it on my database. Its not for displaying on browser. – Dushyant Bangal Jun 14 '16 at 12:01
  • You can store it in your database, that won't be a problem. If you want to solve it not being displayed on your browser, use the function I've written in my answer before printing it. Eg: `document.write(nl2br("hello\nworld"))` – EnKrypt Jun 14 '16 at 13:53
  • Well, my overall aim is very different. Too big to explain what exactly i'm trying to do. Just need to get the code in the UPDATE in question working. – Dushyant Bangal Jun 15 '16 at 06:34
  • 2
    As mentioned in my comments above, this will potentially shift the issue elsewhere. If the external system starts returning a string that's still perfectly valid JSON that's (for example) prettified, eg: `'{\n\t"message":"hello world"\n}'`, this solution will introduce errors, as you'll end up trying to parse `'{\\n\\t"message":"hello world"\\n}'`, which is no longer valid. @DushyantBangal Your first action should be to at least _ask_ the dev on the other system. The fix is potentially trivial for them and is **the correct, most robust long term fix**. – James Thorpe Jun 15 '16 at 08:42
  • @JamesThorpe - Agreed. I assumed that OP had no control over the content being generated by the API endpoint. If that is not the case, he shouldn't have had the original issue to begin with. – EnKrypt Jun 15 '16 at 11:32
  • Yeah, you guys are right, it shouldnt even be an issue. The guy on other end needs to take care of that. Thank you – Dushyant Bangal Jul 01 '16 at 08:34
  • @EnKrypt, can you enlighten me how going from `"\\\\n"` to `"\\n"` fixed it? – Dushyant Bangal Jul 01 '16 at 08:37
  • Simple : `\\n` in the JSON string, will result in `\n` inside the JSON object produced as a result of having been parsed. This is what we want. Making it `\\\\n` would result in `\\n` after parsing which is not a newline character, so it doesn't display right with `console.log()`. You would have to parse it yet again for it to render a newline. – EnKrypt Jul 01 '16 at 11:53