本文实例讲述了JavaScript实现构造json数组的方法。分享给大家供大家参考,具体如下:
从后端拿到的数据是一个数组,每个元素中包含的数据如下(host相同的记录都是相邻的)
currentTime:"1470729601"
host:"10.3.34.21"
taskList:null
taskNum:1
想构造类似如下结构的json数组
[{ name: 'host:10.1.6.49', data: [ [1470641461000, 5], [1470642581000, 4], [1470643701000, 2], [1470647341000, 3] ] }, { name: 'host:10.3.34.18', data: [ [1470641461000, 2], [1470642581000, 2], [1470643701000, 1], [1470647341000, 4] ] }, { name: 'host:10.2.2.22', data: [ [1470641461000, 3], [1470642581000, 2], [1470643701000, 6], [1470647341000, 4] ] },{ name: 'host:10.1.110.96', data: [ [1470641461000, 1], [1470642581000, 8], [1470643701000, 1], [1470647341000, 1] ] },{ name: 'host:10.2.2.87', data: [ [1470641461000, 7], [1470642581000, 3], [1470643701000, 6], [1470647341000, 5] ] }]
错误的方式:
var backendData = data.result; var resultList = new Array(); var curHost = ""; var oneHostDataList = new Array(); for (var i in backendData) { var host = backendData[i].host; if (host != curHost) { if(i != 0) { var item = new Object(); item.name = curHost; item.data = oneHostDataList; resultList.push(item); } oneHostDataList = new Array(); curHost = host; } else { var dot = new Array(); dot.push(backendData[i].currentTime * 1000); dot.push(backendData[i].taskNum); oneHostDataList.push(dot); } } var item = new Object(); item.name = curHost; item.data = oneHostDataList; resultList.push(item); $scope.data = JSON.stringify(resultList);
以上方式的问题在于转换后会使得name和host和带上引号,正确的方式如下:
var backendData = data.result; var resultList = []; var curHost = ""; var oneHostDataList = new Array(); for (var i in backendData) { var host = backendData[i].host; if (host != curHost) { if(i != 0) { var item = { name: curHost, data: oneHostDataList }; resultList.push(item); } oneHostDataList = new Array(); curHost = host; } else { var dot = new Array(); dot.push(backendData[i].currentTime * 1000); dot.push(backendData[i].taskNum); oneHostDataList.push(dot); } } var item = new Object(); item.name = curHost; item.data = oneHostDataList; resultList.push(item); $scope.data = resultList;
PS:这里再为大家推荐几款相关的json在线工具供大家参考:
在线JSON代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat
在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson
json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat
在线json压缩/转义工具:
http://tools.jb51.net/code/json_yasuo_trans
更多关于JavaScript相关内容可查看本站专题:《JavaScript中json操作技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。