使用jQuery更新JSON&;PHP-json_decode()返回空

使用jQuery更新JSON&;PHP-json_decode()返回空,php,jquery,ajax,json,Php,Jquery,Ajax,Json,我正试图将json发布到txt文件,但我的数据有一些问题。每当我检查要在jQuery中发送的数据时,一切看起来都很好,但如果我用php打印出来,我会看到转义斜杠,json_decode会将该数据返回为空。以下是代码片段: jQuery $.ajax({ type : 'POST', url : 'update-json.php', dataType : 'json', data : {json : JSON.stringify([{'name':'Bob'},{'

我正试图将json发布到txt文件,但我的数据有一些问题。每当我检查要在jQuery中发送的数据时,一切看起来都很好,但如果我用php打印出来,我会看到转义斜杠,json_decode会将该数据返回为空。以下是代码片段:

jQuery

$.ajax({
    type : 'POST',
    url : 'update-json.php',
    dataType : 'json',
    data : {json : JSON.stringify([{'name':'Bob'},{'name':'Tom'}])},
    success : function(){
        console.log('success');
    },
    error : function(){
        console.log('error');
    }
});
PHP

<?php
    $json = $_POST['json'];
    $entries = json_decode($json);

    $file = fopen('data-out.txt','w');
    fwrite($file, $entries);
    fclose($file);
?>
PHP ECHO$entries

//EMPTY

看起来您在PHP中启用了magic_引号。一般来说,您应该关闭此功能以避免出现类似的问题。如果不能这样做,则需要对传入字符串调用
stripslashes()

您还可以检查
json\u last\u error()
,找出它无法解码的原因

编辑:下面是您如何输入
stripslashes

$json = stripslashes($_POST['json']);
$entries = json_decode($json);

if( !$entries ) {
     $error = json_last_error();
     // check the manual to match up the error to one of the constants
}
else {

    $file = fopen('data-out.txt','w');
    fwrite($file, $json);
    fclose($file);
}

json\u decode()
的文档中,如果无法解码json,则返回
NULL
。是-我假设由于添加了额外的斜杠,因此无法解码。我想真正的问题是如何修复这些引号但它将
[{\'name\':\'Bob\'},{\'name\':\'Tom\'}]
写入txt文件。有没有办法不显示这些斜杠?在调用
json\u decode
之前,需要调用
stripslashes
。该代码调用
json\u decode
firstThank-我尝试过,但现在它只是将
Array
写入文件。我没有注意到您将
$json
打印到文件中,而不是
$entries
(在上面的代码中)。这是你的意图吗?如果您只是将
$entries
写入文件,我希望它会显示Array。您试图实现的最终结果是什么?您还可以通过执行
print\r($entries)
$json = stripslashes($_POST['json']);
$entries = json_decode($json);

if( !$entries ) {
     $error = json_last_error();
     // check the manual to match up the error to one of the constants
}
else {

    $file = fopen('data-out.txt','w');
    fwrite($file, $json);
    fclose($file);
}