php - how to get around newlines with jQuery.parseJSON - Stack Overflow

When parsing json using jQuery.parseJSON(), I get this errorSyntaxError: JSON.parse: bad control charac

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
 |  Show 1 more ment

1 Answer 1

Reset to default 6

According 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

相关推荐

  • php - how to get around newlines with jQuery.parseJSON - Stack Overflow

    When parsing json using jQuery.parseJSON(), I get this errorSyntaxError: JSON.parse: bad control charac

    2天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信