简体   繁体   English

如何避免PHP返回的JSON中的反斜杠?

[英]How to avoid backslashes in JSON returned from PHP?

I'm having some trouble with the code below. 我在下面的代码上遇到了麻烦。 the console log returns: 控制台日志返回:

"returningList{"view":0,"new":1,"random":1} result: "{\"view\":0,\"new\":1,\"random\":1}""

As you can see it's acquiring backslashes that make it no longer JSON, despite specifying datatype : 'json' . 如您所见,尽管指定了datatype : 'json' ,但它获取的反斜杠使其不再是JSON。

The problem seems to be occurring where the result is read back in from PHP to javascript, because if I write $jsonArr to MySQL before echoing it then the SQL data shows the correct string (ie without the backslashes). 问题似乎发生在从PHP读回结果到javascript的地方,因为如果在回显前将$jsonArr写入MySQL,则SQL数据将显示正确的字符串(即不带反斜杠)。

Please help because this apparent insanity is really winding me up. 请帮忙,因为这种明显的精神错乱确实使我不知所措。 All I want to do is get my data back – In my actual code I don't normally return the JSON I passed in as data, but here it suffices to prove the point. 我要做的就是取回数据–在我的实际代码中,我通常不返回作为数据传入的JSON,但在此足以证明这一点。 I thought that the 'json' datatype would mean that it would accept echoed JSON without corrupting it. 我以为'json'数据类型意味着它可以接受回传的JSON而不会破坏它。

Apologies for the following bluntness, but in response to similar questions I've seen people just say "it escapes the quotes", as if that that answers the question – in this case at least it seems that it doesn't: Obviously (AFAIK) that's where the backslashes are coming from, but the quotes are part of the JSON syntax (which it knows it's expecting), not part of the field content, so they clearly shouldn't be escaped. 对于以下直言不讳的歉意,但在回答类似问题时,我看到人们只是说“它避开了引号”,好像这可以回答问题–在这种情况下,至少似乎没有:(显然(AFAIK )就是反斜杠的来源,但是引号是JSON语法的一部分(它知道这是期望的),而不是字段内容的一部分,因此显然不应转义。 I need a solution please. 我需要一个解决方案 Thanks. 谢谢。

window.newGot = listBuild({
    'view' : 0,
    'new' : 1,
    'random' : 1
});

function listBuild(options)
    //Fill the new list.
    return $.ajax({
        type : "POST",
        url : "./php/getList.php",
        cache : false,
        data : {
            options : JSON.stringify(options)
        },
        datatype : "json"
    }).then(function(jsonList) {
        console.log('returningList' + JSON.stringify(options) + ' result: ' + JSON.stringify(jsonList));
        return jsonList;
    });
}

Here's the php file contents: 这是php文件的内容:

<?php
$options = json_decode($_POST['options'], true);
$jsonArr = json_encode($options);
echo $jsonArr;

Whatever's generating the JSON is probably double-encoding, eg 生成JSON的任何内容都可能是双重编码,例如

$arr = array();
foreach($data as $foo) {
    $arr[] = json_encode($foo);
}
echo json_encode($arr);

JSON-encoding should be the very last step performed, just before the output to the client occurs. JSON编码应该是在输出到客户端之前即将执行的最后一步。

eg 例如

$foo = 'This is a string';
$foo_step1 = json_encode($foo); // "This is a string"
$foo_step2 = json_encode($foo_step1); // "\"This is a string\""

Depending on where the issue is, it might be because you are using json.stringify, have you tried parsing it as json instead? 根据问题所在,可能是因为您使用的是json.stringify,您是否尝试过将其解析为json?

Jquery has the following if you include the jquery library, otherwise the browser has one as well: $.parseJSON() 如果您包含jQuery库,则jQuery具有以下内容,否则浏览器也具有以下内容:$ .parseJSON()

http://api.jquery.com/jquery.parsejson/ http://api.jquery.com/jquery.parsejson/

The other issues could be that you are double encoding it 其他问题可能是您对它进行了双重编码

Also run it through a validator, that is not valid code 还要通过验证器(不是有效的代码)运行它

http://jsonlint.com/ http://jsonlint.com/

"returningList{"view":0,"new":1,"random":1} result: "{\\"view\\":0,\\"new\\":1,\\"random\\":1}"" “ returningList {” view“:0,” new“:1,” random“:1}结果:” {\\“ view \\”:0,\\“ new \\”:1,\\“ random \\”:1}“ “

This is what I would expect the json to look like 这就是我希望json看起来像的样子

{
"returningList": {
    "view": 0,
    "new": 1,
    "random": 1
},
"result": {
    "view": 0,
    "new": 1,
    "random": 1
}

} }

Apparently jsonList is the JSON string, not the decoded object that it represents. 显然jsonList是JSON字符串,而不是它表示的已解码对象。 So when you call JSON.stringify() on it, you're re-encoding the string. 因此,当您对其调用JSON.stringify()时,您正在重新编码字符串。

When you specify dataType: 'json' , jQuery is supposed to decode the response automatically. 当您指定dataType: 'json' ,jQuery应该自动解码响应。 I know it does this when you specify the callback in the success: option, but it looks like it doesn't do it when you use .then() . 我知道当您在success:选项中指定回调时,它会执行此操作,但是当您使用.then()时,它似乎没有执行此操作。 Try using .done() instead. 尝试改用.done()

With that said, I tried to reproduce your result at jsfiddle, and couldn't. 话虽如此,我试图在jsfiddle上重现您的结果,但是不能。

http://jsfiddle.net/barmar/53jthkyu/4/ http://jsfiddle.net/barmar/53jthkyu/4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM