2

When parsing a JSON object I am getting "bad control character" error in the Firebug console. There are lot of questions and solutions in this site; but I am unable to crack this issue. I believe I am doing something silly. Please point me to my mistake.

JS Fiddle: http://jsfiddle.net/Purus/Eqz2r/

If we change the json data to a plain text instead of html tags, it works.

Error:

SyntaxError: JSON.parse: bad control character in string literal
someVal = JSON.parse(sign);

NOTE:

  • The JSON data is obtained from a PHP function using json_encode function.
  • The json output looks valid in jsonlint

Below is the code I have used.

$(document).ready(function () {
   var sign = '{"data":"<br\/><br\/>----------<br \/>\r\nFrom Yahoo Team<br \/>\r\n<a href=\"http:\/\/localhost\/base\/1-yahoo-logo.jpg\" target=\"_blank\"><img style=\"padding: 5px;\" src=\"http:\/\/localhost\/plugins\/1-yahoo-logo.jpg\" height=\"120\" width=\"196\" \/><\/a>"}';

   someVal = JSON.parse(sign);
   $(".demo").append(someVal.data);
});

3 Answers 3

9

You need to escape your escapes :)

Use double \\ instead of \

http://jsfiddle.net/Eqz2r/2/

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. But how can I do that in PHP before passing on the JSON in JS.
actually, replace on server side or js side I guess it doesn't matter?
Thats great news. I could not understand what to replace with what. In your fiddle, I see sign.replace("\n", "\n") which I could not make sense replacing same char by itself.
When I try sign.replace("\", "\\") it says illegal character. I am pretty new to JS. Please bear with me.
that was carried over from your fiddle ;). Try doing it on the php side, i'm not familiar with php but you need to swap single slashes for double (try this i found: str_replace("\\", "\\\\", $data);)
|
4
var s= JsonString;
$.parseJSON(s.replace(/\s+/g,""));

Comments

2

The problem is the \r and \n. These need to be escaped as

\\r 

and

\\n 

in the JSON string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.