存储嵌套JSON对象时出现问题


Problems storing nested JSON objects

有人能帮助我如何在不添加引号的情况下将一个JSON对象作为字段传递给另一个吗?基本上,我有一个函数,在某些情况下,它需要能够将一个"头"附加到一组预先解析为JSON的数据上,或者在其他情况下只解析数据。

问题是,在我尝试传递一个JSON对象以作为标头的"有效负载"存储之前,一切都很好,此时JSON会因为附加了一组额外的引号而变得无效。

我尝试使用的对象是:

{
    "header": {
        "table": "user",
        "action": "insert",
        "opType": "string",
        "message": "Insert sucessful for user: 6",
        "start of records": false,
        "end of records": true
    },
    "data": "[
        {
            "id": "6",
            "Surname": "Peter",
            "Forename": "Kane",
            "Email": "pkane@a.co.uk",
            "Personal_Email": "p.kane@gmail.com",
            "Home_Phone_No": "01216045429",
            "Work_Phone_No": "087852489",
            "Mobile_Phone_No": "77245455598",
            "Address_Line_1": "1aplace",
            "Address_Line_2": "thistown",
            "Address_Line_3": "Someplace",
            "Address_Line_4": "whereever",
            "Post_Code": "W549AJ",
            "Mode_ID": "44",
            "Route_ID": "g12",
            "image": ""
        }
    ]"
}

问题是,在"data"键之后和最后一个curley大括号之前的引号没有这些引号,一切都很好。正如我所说的,我使用PHP,我尝试过regex表达式子字符串等,但似乎什么都不起作用。

我的PHP如下:

 public function dataToJSON($operationType, $table, $action, $data, $message, $header = true, $firstRecord = null) {
    if ((!($operationType) === 'recordSet') and (!($operationType === 'error')) and (!($operationType === 'string') )) {
        throw new Exception("Operation type:" . ' ' . $operationType . ' ' . 'passed to the dataToJSON function not recogonised');
    }
    if (!(is_null($firstRecord))) {
        $isFirstRecord = $firstRecord;
        $isLastRecord = !$firstRecord;
    } else {
        $isFirstRecord = false;
        $isLastRecord = false;
    }
    if ($header) {
        $jsonData = array('header' => array(
                'table' => "$table",
                'action' => "$action",
                'opType' => "$operationType",
                'message' => "$message",
                'start of records' => $isFirstRecord,
                'end of records' => $isLastRecord),
        );
    } else {
        $jsonData = array();
    }
     $recordSet = array();
    if ($operationType === 'recordSet') {
        while ($row = mysql_fetch_assoc($data)) {
            array_push($recordSet, $row);
        }
        if ($header) {
            $jsonData ['data'] = $recordSet;
            return json_encode($jsonData);
        } else {
            return json_encode($recordSet);
        }
    } else if (($operationType === 'error') || ($operationType === 'string')) {
        if ($header) {
            $jsonData ['data'] = $data;
            return stripslashes(json_encode($jsonData));
        } else {
            return $data;
        }
    }
}

为了使用/解析json,它需要是有效的json。。。而那些CCD_ 1字符使其无效。

在这里粘贴和处理以了解我的意思:http://jsonformat.com/

JSON对象不过是一个字符串。为了实现您想要实现的目标,您可能需要解码并重新编码JSON字符串:

$jsonData['data'] = json_decode($data, TRUE);