3

var jsonString = '{"htmluserresponse":"This is my firs \n test"}';
var jsonObj = JSON.parse(jsonString);
console.log("Test Response------" + jsonObj.htmluserresponse);

JSON.stringify() actually created the string i pass into the jsonString, but JSON.parse fails if the string has \n character.

how to get the valid string ?

Satpal
  • 132,252
  • 13
  • 159
  • 168
Jagan K
  • 1,057
  • 3
  • 15
  • 38

1 Answers1

3

You should escape the backslash: \\n.

var jsonString = '{"htmluserresponse":"This is my firs \\n test"}';
var jsonObj = JSON.parse(jsonString);
console.log("Test Response------" + jsonObj.htmluserresponse);
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • That's a html string, contains lot of < ' " > characters, if I use javascript escape, the entire JSON string quotes are getting escaped. Is there a way to escape only slashes ? – Jagan K Aug 17 '16 at 11:00
  • @JaganK In the real life you don't need to do that. If you `JSON.stringify` your JavaScript object that contains strings with new lines, the system will automatically escape them. However if you wish to create JSON string manually (I wouldn't recommend doing that), you can always escape only the new lines with something like `str.replace(/\n/g, '\\n')`. – VisioN Aug 17 '16 at 11:05
  • For some reasons JSON.stringify() is not doing that for me. – Jagan K Aug 17 '16 at 11:11
  • @JaganK `JSON.stringify` is not supposed to escape your special HTML characters, it only creates a JSON string. If you want to achieve both, then first escape your HTML string and then create a JSON string with `JSON.stringify`. – VisioN Aug 17 '16 at 11:14