2016-04-15 106 views
0

我得到的JSON格式如下如何更改Json格式?

[{ 
    "year": "2015-01-05", 
    "contentTitle": "bus", 
    "aid": 43050500 
}, { 
    "year": "2015-01-14", 
    "contentTitle": "paratransit", 
    "aid": 1435400 
}] 

但我需要的格式如下

[ 
    { 
    "year": "2015-01-05", 
    "bus": 43050500, 
    "paratransit": 1435400, 
    "rail": 174436000 
    }, 
    { 
    "year": "2015-01-14", 
    "bus": 420572700, 
    "paratransit": 1924800, 
    "rail": 168658800 
    }] 

我試圖在一定程度上通過以下

data.forEach(function (d) { 

    var gameName = d.contentTitle; 
    var gameValue = d.aid; 
     d[gameName] = gameValue; 
     d.year = parseformat(d.year); 
     delete d["contentTitle"]; 
     delete d["aid"]; 


    }); 

    alert(JSON.stringify(data)); 

存檔,但我沒有沒有達到預期的效果。

+3

無論你的例子是有效的JSON。 – PeeHaa

+0

雖然複製代碼錯誤發生......這兩個json數據是有效的 –

+0

至少[更新您的問題](http://stackoverflow.com/posts/36644324/edit)與正確的代碼。 – PeeHaa

回答

0

你應該map你的陣列,而不是forEach

data = [{ 
 
    year: "2015-01-05", 
 
    contentTitle: "bus", 
 
    "aid": 43050500 
 
}, { 
 
    year: "2015-01-14", 
 
    contentTitle: "paratransit", 
 
    aid: 1435400 
 
}]; 
 

 
data = data.map(function (d) { 
 
    d[d.contentTitle] = d.aid; 
 
    d.year = d.year; // parseformat me << 
 
    delete d["contentTitle"]; 
 
    delete d["aid"]; 
 

 
    return d; 
 
}); 
 

 
alert(JSON.stringify(data));

+0

感謝kiro給你回覆...但是數據格式不像我預料的那樣你可以看看 –