繁体   English   中英

更改json格式

[英]Change json format

我想使用融合图表创建图表并使用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" }
   ]
}

由于$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);
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小提琴演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM