我有一个巨大的 JSON 文件。它的结构不正确,我无法控制结构。它是来自一组基于时间戳的路由器的数据。我正在尝试创建一个对象结构,它将给定路由器的所有信息组合成一个带有时间戳等的路由器对象作为数组。@quodlibetor 对我接近这一点很有帮助。我还想根据 json 中的名称 val 对的名称自动命名对象的属性。
我的目标是从 json 文件中的名称自动命名属性,并将其重组为一个看起来像这样的对象(我愿意接受有关结构的建议,这似乎是最有组织的方式)。
这是我想要的结构:
{
"Router": [
{
"routerName": "RouterID1",
"TimeStamp": [
"2012/01/01 06:00:00",
"2013/01/01 06:00:00",
"2014/01/01 06:00:00"
],
"OutputBITS": [
"23235",
"29903",
"22103"
],
"InputBITS": [
"23235",
"29903",
"22103"
]
}
]
}
尽管尝试创建该结构,但我已经接近但没有交易:
{
"RouterID1": {
"timeStamp": [
{
"timeStamp": "2012/01/01 06:00:00"
},
{
"timeStamp": "2013/01/01 06:00:00"
},
{
"timeStamp": "2014/01/01 06:00:00"
}
],
"OutputBITS": [
{
"OutputBITS": "23235"
},
{
"OutputBITS": "23235"
},
{
"OutputBITS": "23235"
}
],
"InputBITS": [
{
"InputBITS": "29903"
},
{
"InputBITS": "29903"
},
{
"InputBITS": "29903"
}
]
}
}
原始 JSON:
json = [
{
"Router": "RouterID1",
"TimeStamp": "2012/01/01 06:00:00",
"OutputBITS": "23235",
"InputBITS": "29903"
},
{
"Router": "RouterID1",
"TimeStamp": "2013/01/01 06:00:00",
"OutputBITS": "23235",
"InputBITS": "29903"
},
{
"Router": "RouterID1",
"TimeStamp": "2014/01/01 06:00:00",
"OutputBITS": "23235",
"InputBITS": "29903"
},
{
"Router": "RouterID3",
"TimeStamp": "2012/01/01 06:05:00",
"OutputBITS": "21235",
"InputBITS": "22103"
},
{
"Router": "RouterID3",
"TimeStamp": "2012/01/01 06:05:00",
"OutputBITS": "21235",
"InputBITS": "22103"
},
{
"Router": "RouterID4",
"TimeStamp": "2012/01/01 06:05:00",
"OutputBITS": "21235",
"InputBITS": "22103"
},
{
"Router": "RouterID4",
"TimeStamp": "2012/01/01 06:05:00",
"OutputBITS": "21235",
"InputBITS": "22103"
}
];
代码:
// Create routers object
var routers = {};
for (var i=0;i<json.length;i++){
var router_name = json[i].Router;
router_name = (router_name.replace(/-/g, "")); //take hyphen out or router name
if (!routers[router_name]){
// add properties to the router object thanks to @@quodlibetor
// instead of using timeStamp is something like json[i] or json.[name] or some
// way to reference each json property and not have to type it in?
routers[router_name] = { timeStamp : [], OutputBITS : [], InputBITS : [] };
}
routers[router_name].timeStamp.push({
timeStamp : json[i].TimeStamp
});
routers[router_name].OutputBITS.push({
OutputBITS : json[i].OutputBITS
});
routers[router_name].InputBITS.push({
InputBITS : json[i].InputBITS
});
};
console.log(routers);
});
</script>