php 为什么 json_encode 添加反斜杠?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10314715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:54:04  来源:igfitidea点击:

Why is json_encode adding backslashes?

phpjson

提问by Steven

I've been using json_encodefor a long time, and I've not had any problems so far. Now I'm working with a upload script and I try to return some JSON data after file upload.

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

I have the following code:

我有以下代码:

print_r($result); // <-- This is an associative array
echo json_encode($result); // <-- this returns valid JSON

This gives me the following results:

这给了我以下结果:

// 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}}

Can anyone tell me why json_encodeadds slashes?

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

update

更新

@Quentin said that something is happening between json_encodeand .parseJSONand he's right.

@Quentin 说在json_encode和之间发生了一些事情.parseJSON,他是对的。

Doing a alert(data.toSource());gives me the dollowing result:

做 aalert(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})

And this is not valid JSON. It also adds the status:200and I have no idea where this comes from.

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

Could it be that the Plupload binddoes something to my returned data?

难道是Plupload bind对我返回的数据做了什么?

This is my js script:

这是我的js脚本:

  uploader.bind('FileUploaded', function(up, file, data) {
    alert(data.toSource());
    $('#' + file.id + " b").html("100%");
  });

采纳答案by Quentin

Can anyone tell me why json_encode adds slashes?

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

Forward slash characters can cause issues (when preceded by a <it triggers the SGML rules for "end of script element") when embedded in an HTML script element. They are escaped as a precaution.

<当嵌入到 HTML 脚本元素中时,正斜杠字符可能会导致问题(当前面有一个时,它会触发“脚本元素结束”的 SGML 规则)。他们被逃脱作为预防措施。

Because when I try do use jQuery.parseJSON(response); in my js script, it returns null. So my guess it has something to do with the slashes.

因为当我尝试使用 jQuery.parseJSON(response); 在我的 js 脚本中,它返回 null。所以我猜这与斜线有关。

It doesn't. In JSON "/"and "\/"are equivalent.

它没有。在 JSON 中"/""\/"是等价的。

The JSON you list in the question is valid (you can test it with jsonlint). Your problem is likely to do with what happens to it between json_encodeand parseJSON.

您在问题中列出的 JSON 是有效的(您可以使用jsonlint对其进行测试)。您的问题可能与json_encode和之间发生的事情有关parseJSON

回答by reirracon

Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4).

只需使用“JSON_UNESCAPED_SLASHES”选项(在 5.4 版后添加)。

json_encode($array,JSON_UNESCAPED_SLASHES);

回答by Meezaan-ud-Din

I just came across this issue in some of my scripts too, and it seemed to be happening because I was applying json_encode to an array wrapped inside another array which was also json encoded. It's easy to do if you have multiple foreach loops in a script that create the data. Always apply json_encode at the end.

我也刚刚在我的一些脚本中遇到了这个问题,它似乎正在发生,因为我将 json_encode 应用于包装在另一个也是 json 编码的数组中的数组。如果在创建数据的脚本中有多个 foreach 循环,这很容易做到。始终在最后应用 json_encode。

Here is what was happening. If you do:

这就是正在发生的事情。如果你这样做:

$data[] = json_encode(['test' => 'one', 'test' => '2']);
$data[] = json_encode(['test' => 'two', 'test' => 'four']);
echo json_encode($data);

The result is:

结果是:

["{\"test\":\"2\"}","{\"test\":\"four\"}"]

So, what you actually need to do is:

所以,你真正需要做的是:

$data[] = ['test' => 'one', 'test' => '2'];
$data[] = ['test' => 'two', 'test' => 'four'];
echo json_encode($data);

And this will return

这将返回

[{"test":"2"},{"test":"four"}]

回答by Mayank

This happens because the JSON format uses ""(Quotes) and anything in between these quotes is useful information (either key or the data).

发生这种情况是因为 JSON 格式使用 ""(Quotes) 并且这些引号之间的任何内容都是有用的信息(键或数据)。

Suppose your data was : He said "This is how it is done".Then the actual data should look like "He said \"This is how it is done\".".

假设您的数据是:He said "This is how it is done".那么实际数据应该是这样的"He said \"This is how it is done\"."

This ensures that the \"is treated as "(Quotation mark)and not as JSON formatting. This is called escape character.

这确保\"被视为"(Quotation mark)JSON 格式而不是 JSON 格式。这称为escape character.

This usually happens when one tries to encode an already JSON encoded data, which is a common way I have seen this happen.

这通常发生在人们试图对已经 JSON 编码的数据进行编码时,这是我见过这种情况的一种常见方式。

Try this

尝试这个

$arr = ['This is a sample','This is also a "sample"']; echo json_encode($arr);

$arr = ['This is a sample','This is also a "sample"']; echo json_encode($arr);

OUTPUT:

输出:

["This is a sample","This is also a \"sample\""]

回答by Jesus Walker

I had a very similar problem, I had an array ready to be posted. in my post function I had this:

我有一个非常相似的问题,我有一个准备发布的数组。在我的帖子功能中,我有这个:

json = JSON.stringfy(json);

the detail here is that I'm using blade inside laravel to build a three view form, so I can go back and forward, I have in between every back and forward button validations and when I go back in the form without reloading the page my json get filled by backslashes. I console.log(json)in every validation and realized that the json was treated as a string instead of an object.

这里的细节是,我在 laravel 中使用刀片来构建一个三视图表单,所以我可以前后移动,我在每个后退和前进按钮验证之间都有,当我在不重新加载页面的情况下返回表单时json 被反斜杠填充。我console.log(json)在每次验证中都意识到 json 被视为字符串而不是对象。

In conclution i shouldn't have assinged json = JSON.stringfy(json)instead i assigned it to another variable.

总而言之,我不应该json = JSON.stringfy(json)分配,而是将其分配给另一个变量。

var aux = JSON.stringfy(json);

This way i keep json as an object, and not a string.

这样我将 json 作为一个对象,而不是一个字符串。

回答by Vipin Jain

json_encodewill always add slashes.

json_encode将始终添加斜杠。

Check some examples on the manual HERE

此处查看手册中的一些示例

This is because if there are some characters which needs to escaped then they will create problem.

这是因为如果有一些字符需要转义,那么它们就会产生问题。

To use the json please Parse your json to ensure that the slashes are removed

要使用 json,请解析您的 json 以确保删除斜杠

Well whether or not you remove slashesthe json will be parsed without any problem by eval.

好吧,无论您是否删除斜杠, eval 都会毫无问题地解析 json。

<?php
$array = array('url'=>'http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg','id'=>54);
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var x = jQuery.parseJSON('<?php echo json_encode($array);?>');
alert(x);
</script>

This is my code and i m able to parse the JSON.

这是我的代码,我能够解析 JSON。

Check your code May be you are missing something while parsing the JSON

检查您的代码可能是您在解析 JSON 时遗漏了一些东西