json_decode无法在php中运行

时间:2016-09-01 13:27:36

标签: php json

请检查我的下面的代码,请让我知道我正在做的错误,我只想解码json并在浏览器上打印为数组

<?php

$json = '{
"Token" : "xxx-xxx-xxx",
"ID": "1",
"Recipients": [
    {
        "Recipient_ID": "XX",
        "From_Name": "XXX",
        "From_Email": "XXX",
        "To_Name": "XXX",
        "To_Email": "XXX",
        "Subject": "XXX",
        "Message": "XXX",
        "Attachments": [
            {
                "File_Name": "XXX",
                "File_Path": "XXX",
            }
        ],
    }
],
}';

$input = $json;
print_r(json_decode(stripslashes($input)));

?>

我试过这个json字符串在线解码(http://jsonviewer.stack.hu/)并且它的工作正常,所以json字符串没有问题。任何帮助都会很感激。

2 个答案:

答案 0 :(得分:2)

<?php

$json = '{
    "Token": "xxx-xxx-xxx",
    "ID": "1",
    "Recipients": [{
        "Recipient_ID": "XX",
        "From_Name": "XXX",
        "From_Email": "XXX",
        "To_Name": "XXX",
        "To_Email": "XXX",
        "Subject": "XXX",
        "Message": "XXX",
        "Attachments": [{
            "File_Name": "XXX",
            "File_Path": "XXX"
        }]
    }]
}';

$input = $json;
var_dump(json_decode(stripslashes($input)));

?>

答案 1 :(得分:0)

问题从你所拥有的json格式开始......你有一些','需要被删除,这就是为什么json_decode()无法完成他的工作。此函数抛出错误异常,但您应该做一个小技巧来查看错误。 您可以使用此代码查看错误。

for (x=0; x<5; x++){
    printf("loop %d\n",x);
.
.
.

你json应该是这样的。

switch (json_last_error()) {
    case JSON_ERROR_NONE:
        echo ' - No errors';
    break;
    case JSON_ERROR_DEPTH:
        echo ' - Maximum stack depth exceeded';
    break;
    case JSON_ERROR_STATE_MISMATCH:
        echo ' - Underflow or the modes mismatch';
    break;
    case JSON_ERROR_CTRL_CHAR:
        echo ' - Unexpected control character found';
    break;
    case JSON_ERROR_SYNTAX:
        echo ' - Syntax error, malformed JSON';
    break;
    case JSON_ERROR_UTF8:
        echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
    break;
    default:
        echo ' - Unknown error';
    break;
}