When parsing json using jQuery.parseJSON(), I get this error
SyntaxError: JSON.parse: bad control character in string literal
A quick search revelead that this is caused by newlines in the json string.
I get my json string from PHP using json_encode().
Is there a way to encode it in such a way that jQuery.parseJSON() would not plain and still retain the newline information?
When parsing json using jQuery.parseJSON(), I get this error
SyntaxError: JSON.parse: bad control character in string literal
A quick search revelead that this is caused by newlines in the json string.
I get my json string from PHP using json_encode().
Is there a way to encode it in such a way that jQuery.parseJSON() would not plain and still retain the newline information?
Share Improve this question asked Aug 15, 2012 at 8:41 developarvindeveloparvin 5,05912 gold badges57 silver badges101 bronze badges 6- 1 Never had this issue before....strange, because json doesn't really care about whitespace. – pho Commented Aug 15, 2012 at 8:42
- You can use Javascript's inbuilt JSON.parse – pho Commented Aug 15, 2012 at 8:43
- Can you post the PHP array and the result from parseJSON? – Ben Swinburne Commented Aug 15, 2012 at 8:43
- Unless of course you're leaving a string unterminated when you end the line. That is invalid JSON, and if you're using PHP to create the json that shouldn't happen – pho Commented Aug 15, 2012 at 8:45
-
Are you able to post the actual JSON itself? You can use
console.log(yourJson)
before you parse it and than post the result. Would be much easier to analyse a possible solution. – Nope Commented Aug 15, 2012 at 8:50
1 Answer
Reset to default 6According to the v8 bug tracker (http://code.google./p/v8/issues/detail?id=616), this is actually the correct behavior:
"Newlines are not allowed inside JSON strings (no control characters are, see, e.g., JsonStringCharacter production of ECMA262 5ed, section 15.2.1.1)."
So it depends really on what you want to do - in this instance, as you need the newlines, you need to escape them before doing the json parse:
//myjsonobject contains the json object
var obj = jQuery.parseJSON(myjsonobject.replace(/\n/g,"\\n"));
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744826662a4595838.html
评论列表(0条)