2013-04-17 111 views
0

我想用融合圖表創建圖表之前使用JSON作爲數據格式更改JSON格式

如果我的數據是這樣的:

{ 
"items": [ 
    { 
     "2013-03-28": 1771, 
     "2013-03-29": 1585, 
     "2013-03-30": 1582, 
     "2013-03-31": 1476 
    } 
    ] 
} 

我得到了處理使用PHP上面的數據:

<?php 
$param = $_GET['myparam']; 

$Data = file_get_contents("http://mylink.com/proccess.php?output=json"); 

$Proses2 = json_decode($Data); 

$array = array(); 
$array[] = (object)$Proses2; 

if ($_GET['callback']) { 
    echo $_GET['callback'] . '('.json_encode($array).')'; 
}else{ 
    echo '{"items":'. json_encode($array) .'}'; 
} 

如何更改數據,使其變得像這樣的圖表中使用的格式?

{ 
    "chart": { 
     "caption" : "Weekly Sales Summary" , 
     "xAxisName" : "Week", 
     "yAxisName" : "Sales", 
     "numberPrefix" : "$" 
}, 

"data" : 
    [ 
     { "label" : "Day 1", "value" : "14400" }, 
     { "label" : "Day 2", "value" : "19600" }, 
     { "label" : "Day 3", "value" : "24000" }, 
     { "label" : "Day 4", "value" : "15700" } 
    ] 
} 

後來成爲:

{ 
    "chart": { 
     "caption" : "Weekly Sales Summary" , 
     "xAxisName" : "Week", 
     "yAxisName" : "Sales", 
     "numberPrefix" : "$" 
}, 

"data" : 
    [ 
     { "label" : "2013-03-28", "value" : "1771" }, 
     { "label" : "2013-03-29", "value" : "1585" }, 
     { "label" : "2013-03-30", "value" : "1582" }, 
     { "label" : "2013-03-31", "value" : "1476" } 
    ] 
} 
+0

因爲'$ Proses2'是一個對象(stdClass的),你可以輕鬆地添加新的特性,比如'chart'和'data',用'items'填補他們終於卸下'項目'物業 – MatRt

+0

@MatRt你能幫我舉個例子嗎? –

回答

2
var item = { 
    "items":{ 
     "2013-03-28": "1771", 
     "2013-03-29": "1585", 
     "2013-03-30": "1582", 
     "2013-03-31": "1476" 
     } 
    }; 

var data = [];temp=0; 
for(var key in item.items) 
{ 
alert(key);alert(item.items[key]); 
data.push({}); 
data[temp].label = key; 
data[temp].value = item.items[key]; 
temp++; 
} 
alert(JSON.stringify(data)); 

JS Fiddle Demo

2

作爲$Proses2是一個基本的對象(stdClass),你可以輕鬆地添加新的屬性,如chartdata,你想要什麼(在這種情況下,數據填充它們從items),最後除去items屬性

下面是一個例子:

<?php 

// The json 
$json = '{"items":[{"2013-03-28":1771,"2013-03-29":1585,"2013-03-30":1582,"2013-03-31":1476}]}'; 

// Extract the json to a STD class object 
$object = json_decode($json); 

// print the actual object 
print_r($object); 

// modify object by adding new property 
$object->chart = array(
    "caption" =>"Weekly Sales Summary", 
    "xAxisName" => "Week", 
    "yAxisName" => "Sales", 
    "numberPrefix" => "$" 
); 

// Remove previous property 
unset($object->items); 

print_r($object); 
+0

謝謝@MatRt,我會盡力的 –