我无法解析JSON编码字符串中的数据

时间:2013-06-25 21:07:52

标签: php json

我正在尝试从JSON编码的字符串中解析一些选项数据。这是我已有的代码:

<?php
$json = json_decode('{"1":"{\"QID\":\"1\",\"Type\":\"MC\",\"Question\":\"Question here\",\"Options\":{\"1\":\"Answer Opt 1\"}}"}');
foreach ($json as $QID => $Data) {
echo "QID: $QID, Type: ";
$new = json_decode(stripslashes($Data));
if($new->Type=="MC"){
    echo "Multiple Choice, Question: ".$new->Question.", Options: ";
    $options = json_decode($new->Options,true);
}else{
    echo "Unknown";
}
echo ".<br/>";
}
?>

提供的JSON字符串是发送到脚本的内容,我得到的错误是:

json_decode() expects parameter 1 to be string, object given

$ new-&gt;选项的VarDump是:

object(stdClass)#3 (1) { ["1"]=> string(1) "2" }

1 个答案:

答案 0 :(得分:0)

JSON格式不正确。 在我执行stripslashes后,JSON应该像以下一样形成有效:

{
    "1": {
        "QID": "1",
        "Type": "MC",
        "Question": "Questionhere",
        "Options": {
            "1": "AnswerOpt1"
        }
    }
}