使用php和解析编码json

时间:2015-01-19 15:59:44

标签: php json parsing

我需要创建两个变量来运行具有此结构的js

var sets = [{"label":"PHP","size":"6"},{"label":"SQL","size":"1"}];

var overlaps = [ {"sets":[0,1],"size":"0"}];

我正在尝试使用php创建它,就像这样

$sets[] = array("label" =>"PHP", "size" => "6");
$overlaps[] = array("sets" => array(0,1), "size" => "0");
print json_encode(array($sets, $overlaps));

在ajax中我这样做

$.post(action
        , {param:param}
        , function(returned_data){

            console.log(returned_data);
            var json = $.parseJSON(returned_data);
            sets = json[0];
            overlaps = json[1];
});

Console.log转储此

[[{"label":"PHP","size":"6"},{"label":"SQL","size":"1"},{"label":"JQuery","size":"1"}],[{"sets":[0,2],"size":"1"}]]

错误是“无法读取属性'推送'未定义

怎么了?如何解析json并将每个部分分配给变量?

3 个答案:

答案 0 :(得分:1)

我认为您不需要将其解析为JSON,控制台暗示它已经是一个对象。此外,return几乎是所有语言中的保留字(语言结构),因此您应养成不将其用于变量名称的习惯。

$.post(action
    , {param:param}
    , function(return_data){
        return_data = typeof return_data=='object' ? return_data : $.parseJSON(return_data);
        //The line above parses the string only if the browser didn't already recognize it as a JSON-object.

        console.log(return_data);
        sets = return_data[0];
        overlaps = return_data[1];
   });

此外,您应该在PHP中设置标题(当然不需要$.parseJSON):

$sets[] = array("label" =>"PHP", "size" => "6");
$overlaps[] = array("sets" => array(0,1), "size" => "0");
header('Content-type: application/json'); //I added this line
echo json_encode(array($sets, $overlaps));

答案 1 :(得分:1)

奇怪的错误。可能是因为您使用保留字作为变量。

答案 2 :(得分:1)

jQuery $.post已经预期JSON,因此不需要 JSON解析

$.post(action
    , {param:param}
    , function(returned_data){

        console.log(returned_data);
        var json = returned_data;
        sets = json[0];
        overlaps = json[1];
});