为了账号安全,请及时绑定邮箱和手机立即绑定

为什么json_encode添加反斜杠?

为什么json_encode添加反斜杠?

PHP
呼如林 2019-11-02 11:01:17
我已经使用json_encode了很长时间了,到目前为止我还没有遇到任何问题。现在,我正在使用上传脚本,并且尝试在文件上传后返回一些JSON数据。我有以下代码:print_r($result); // <-- This is an associative arrayecho json_encode($result); // <-- this returns valid JSON这给了我以下结果:// print_r resultArray(    [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%");  });
查看完整描述

3 回答

?
桃花长相依

TA贡献1860条经验 获得超8个赞

发生这种情况是因为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\""]


查看完整回答
反对 回复 2019-11-02
  • 3 回答
  • 0 关注
  • 1443 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信