parseJSON失败,而json_decode工作

时间:2014-08-20 08:40:31

标签: jquery json

我已经苦苦挣扎了一段时间,我有一个存储在DB中的字符串化JSON对象,一旦我检索它我用PHP和jQuery解码它,PHP工作正常,jQuery失败,继承人代码< / p>

var data = $.parseJSON('{"page_name":"Test page","page_title":"Test title","site":"0","page_url":"http:\/\/saulius.epickitdev.com\/test-page","page_type":"1","bg_type":"gradient","background_img_url":"","fill_bg_color":"","background_color":"","background_gradient_top":"5194c4","background_gradient_bottom":"000000","video_type":"yt","youtube_video_url":"","youtube_video_start_from":"","mp4_video_url":"","webm_video_url":"","ogg_video_url":"","width_type":"fixed","width_padding":"10","layout_color":"cc25cc","border_size":"3","border_color":"5a7de6","container_position":"middle","container_position_left":"","container_position_right":"","meta_title":"mtest","meta_description":"mdesc","meta_keyword":"mkey","fb_title":"ftitle","fb_description":"fdesc","header_script":{"1":"<meta name=\"keywords\" content=\"h1\">","2":"<meta name=\"keywords\" content=\"h2\">"},"footer_script":[""],"redirect_url":"","exit_message":""}');
        console.log(data);

现在它告诉我错误是:

  

SyntaxError:JSON.parse:expected&#39;,&#39;或者&#39;}&#39;}在JSON数据的第1行第766行的对象中的属性值之后

这将是&#39; =&#39;的:

"<meta name=\"keywords\" content=\"h1\">"

任何人都有线索吗?我尝试了不同的解析器,我完全坚持了这个!

1 个答案:

答案 0 :(得分:6)

您需要将字符串中的\字符双重编码为​​\\

var s = '{"page_name":"Test page","page_title":"Test title","site":"0","page_url":"http://saulius.epickitdev.com/test-page","page_type":"1","bg_type":"gradient","background_img_url":"","fill_bg_color":"","background_color":"","background_gradient_top":"5194c4","background_gradient_bottom":"000000","video_type":"yt","youtube_video_url":"","youtube_video_start_from":"","mp4_video_url":"","webm_video_url":"","ogg_video_url":"","width_type":"fixed","width_padding":"10","layout_color":"cc25cc","border_size":"3","border_color":"5a7de6","container_position":"middle","container_position_left":"","container_position_right":"","meta_title":"mtest","meta_description":"mdesc","meta_keyword":"mkey","fb_title":"ftitle","fb_description":"fdesc","header_script":{"1":"<meta name=\\"keywords\\" content=\\"h1\\">","2":"<meta name=\\"keywords\\" content=\\"h2\\">"},"footer_script":[""],"redirect_url":"","exit_message":""}'
$.parseJSON(s)

这是因为它们在字符串内的字符串内转义。

顶级字符串是整个值,因此展开一个级别的转义会导致这一点,

{"1":"<meta name="keywords" content="h1">"} #Invalid JSON

这是无效的,因为值中的引号不再被转义,因为顶层JavaScript字符串解包它们。当JavaScript解释器读入该字符串文字时,所有\个字符都将被解包为一个级别,这意味着\"变为"。然后需要处理JSON字符串,但它不再有效,因为您打算转义的引号现在未转义(实际上它们从来都不是真正转义,它们就是这样。 )当你使用单引号时,你不需要转义",但你总是可以逃避任何,如果它不是特殊字符,它就什么都不做。

因此,为了在处理顶级字符串后仍然转义引号,您需要转义\本身。

var s = '{"1":"<meta name=\\"keywords\\" content=\\"h1\\">"}'
console.log(s) //'{"1":"<meta name=\"keywords\" content=\"h1\">"}'
$.parseJSON(s)