如何从JSON中提取以创建新的JSON文件

时间:2013-07-31 11:23:26

标签: jquery ajax json

我有动态来自数据库的JSON数据,见下文:

[["15","0.027","0.137","0.353","0.044","0.111","0.024","2013-07-30 17:45:06"],["17","0.027","0.137","0.353","0.044","0.111","0.024","2013-07-30 17:50:14"],["19","0.017","0.137","0.353","0.044","0.111","0.024","2013-07-30 17:55:35"],["21","0.017","0.137","0.353","0.044","0.111","0.024","2013-07-30 18:00:34"],["23","0.017","0.137","0.353","0.044","0.111","0.024","2013-07-30 18:05:10"],["25","0.017","0.137","0.353","0.044","0.111","0.024","2013-07-30 18:10:07"] and so on..

所以结构如下[time1, time2, time3, time4, time5, time5, time7, TimeStamp]

我需要实现的是最终得到7个新JSON,其结构如下:

json1 = [time1,TimeStamp]
json2 = [time2,TimeStamp]
json3 = [time3,TimeStamp]
json4 = [time4,TimeStamp]
and so on..

我需要将其实现到jQPLot中 有人可以帮忙吗?谢谢

1 个答案:

答案 0 :(得分:0)

选中此项(您可以找到ready-to-play jsfiddle here):

// Creates a new array from the items array with the item 
// for the given index and with the last item (timestamp).
function timeNFromItems(items, index) {
    return [items[index], items[items.length - 1]];
}

// Loop over each time index, so that from:
// [time1, time2, time3, time4, time5, time6, time7, timestamp]
// ...the following is printed out:
// time1, timestamp
// time2, timestamp
// [...]
// time7, timestamp
function timesFromItems(items) {
    numberOfTimes = 7;
    result = "";
    for (var i = 0; i < numberOfTimes; ++i) {
        result += timeNFromItems(items, i) + "\n";
    }
    return result;
}

sample = [
    ["15", "0.027", "0.137", "0.353", "0.044", "0.111", "0.024", "2013-07-30 17:45:06"],
    ["17", "0.027", "0.137", "0.353", "0.044", "0.111", "0.024", "2013-07-30 17:50:14"],
    ["19", "0.017", "0.137", "0.353", "0.044", "0.111", "0.024", "2013-07-30 17:55:35"],
    ["21", "0.017", "0.137", "0.353", "0.044", "0.111", "0.024", "2013-07-30 18:00:34"],
    ["23", "0.017", "0.137", "0.353", "0.044", "0.111", "0.024", "2013-07-30 18:05:10"],
    ["25", "0.017", "0.137", "0.353", "0.044", "0.111", "0.024", "2013-07-30 18:10:07"]
];

alert(timesFromItems(sample[0]));

第一个函数获取一个给定的“行”对,第二个函数只是循环以获取所有对。