使用jquery格式化json数据到特定格式

时间:2013-11-14 18:20:49

标签: jquery json

我正在尝试使用flot构建一个饼图,并从服务器获取json数据,如下所示

[
  {"transactions": 7, "products__name": "mark"}, 
  {"transactions": 12, "products__name": "vicky"}, 
  {"transactions": 30, "products__name": "daniel"},   
  {"transactions": 6, "products__name": "hurray "}]

所以我需要将上面的词典列表格式化为以下格式,以便我可以使用它直接插入flot饼图聊天placeholder

data = [
    { label: "mark",  data: 7, color: "#4572A7"},
    { label: "vicky",  data: 12, color: "#80699B"},
    { label: "daniel",  data: 30, color: "#3D96AE"},
    { label: "hurray",  data: 6, color: "#89A54E"},
];

其实我只想用jqueryforeach或其他东西来做这件事。

1 个答案:

答案 0 :(得分:3)

lst = [
  {"transactions": 7, "products__name": "mark"}, 
  {"transactions": 12, "products__name": "vicky"}, 
  {"transactions": 30, "products__name": "daniel"},   
  {"transactions": 6, "products__name": "hurray "}]
colors = ["#4572A7", "#80699B", "#3D96AE", "#89A54E"]
data = []

for i, c in zip(lst, colors):
   data.append({'label': i['products__name'], 'data': i["transactions"], 'color': c,})