为什么json_encode添加反斜杠?

我已经使用json_encode了很长时间了,到目前为止我还没有遇到任何问题。现在,我正在使用上传脚本,并且尝试在文件上传后返回一些JSON数据。


我有以下代码:


print_r($result); // <-- This is an associative array

echo json_encode($result); // <-- this returns valid JSON

这给了我以下结果:


// print_r result

Array

(

    [logo_url] => http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg

    [img_id] => 54

    [feedback] => Array

        (

            [message] => File uploaded

            [success] => 1

        )


)


// Echo result

{"logo_url":"http:\/\/mysite.com\/uploads\/gallery\/7f\/3b\/f65ab8165d_logo.jpeg","img_id":"54","feedback":{"message":"File uploaded","success":true}}

谁能告诉我为什么加json_encode斜杠?


更新


@Quentin说,事情是发生之间json_encode以及.parseJSON和他是对的。


做一个alert(data.toSource());给我以下结果:


({response:"{\"logo_url\":\"http:\\/\\/storelocator.com\\/wp-content\\/uploads\\/gallery\\/7f\\/3b\\/71b9520cfc91a90afbdbbfc9d2b2239b_logo.jpeg\",\"img_id\":\"62\",\"feedback\":{\"message\":\"File uploaded\",\"success\":true}}", status:200})

这不是有效的JSON。它还添加status:200,我不知道它来自哪里。


可能Plupload bind对我返回的数据有影响吗?


这是我的js脚本:


  uploader.bind('FileUploaded', function(up, file, data) {

    alert(data.toSource());

    $('#' + file.id + " b").html("100%");

  });


呼如林
浏览 1444回答 3
3回答

桃花长相依

发生这种情况是因为JSON格式使用“”(引号),并且这些引号之间的任何内容都是有用的信息(键或数据)。假设您的数据是:He said "This is how it is done". 那么实际数据应该看起来像"He said \"This is how it is done\"."。这样可确保将\"视为"(Quotation mark)而不是JSON格式。这称为escape character。当人们尝试对已经JSON编码的数据进行编码时,通常会发生这种情况,这是我所见过的一种常见方式。尝试这个$arr = ['This is a sample','This is also a "sample"'];echo json_encode($arr);输出:["This is a sample","This is also a \"sample\""]
打开App,查看更多内容
随时随地看视频慕课网APP