php json到javascript json格式不符合要求的结果

时间:2017-11-04 14:24:19

标签: javascript php jquery arrays json

我正在努力实现以下json 很抱歉,但我不知道哪个是问题。

需要使用控制台拍摄JSON屏幕:https://imgur.com/a/3HyI9

var requiredJson = {
        chart: {
            container: "#OrganiseChart-simple"
        },      
        nodeStructure: {text:{name:"Root"},children:[{text:{name:"naresh"},children:[{text:{name:"rahul1"}},{text:{name:"rahul123"}},{text:{name:"kapil1"},children:[{text:{name:"priya12"},children:[{text:{name:"amit12"}}]}]}]},{text:{name:"roshan"}},{text:{name:"Seppl"}},{text:{name:"pankaj1910"}}]}
    };

我的尝试:

我的尝试是给我这个结果:https://imgur.com/a/x1hot

当我使用echo到json_encode($ tree)时,我的php json:

[{"text":{"name":"Root"},"children":[{"text":{"name":"naresh"},"children":[{"text":{"name":"rahul1"}},{"text":{"name":"rahul123"}},{"text":{"name":"kapil1"},"children":[{"text":{"name":"priya12"},"children":[{"text":{"name":"amit12"}}]}]}]},{"text":{"name":"roshan"}},{"text":{"name":"Seppl"}},{"text":{"name":"pankaj1910"}}]}] ;

//$tree is a php array

var mytry = '<?php echo json_encode($tree); ?>';
 var requiredJson  = {
        chart: {
            container: "#OrganiseChart-simple"
        },

        nodeStructure: mytry 
    };

JS FIDDLE:https://jsfiddle.net/ueo0k9ys/1/

1 个答案:

答案 0 :(得分:2)

删除php输出周围的引号。他们告诉javascript编译器它是一个字符串而不是数组

var mytry = <?php echo json_encode($tree); ?>;
var requiredJson  = {
    chart: {
        container: "#OrganiseChart-simple"
    },

    nodeStructure: mytry 
};