我有一组简单的 JSON 需要重新格式化,因为并非总是输出所有键值对。
{
"result": [
{
"category": "Negative Notification",
"event": "open",
"result": 2
},
{
"category": "Referral",
"event": "bounce",
"result": 1
},
{
"category": "Negative Notification",
"event": "delivered",
"result": 34
},
{
"category": "Negative Notification",
"event": "processed",
"result": 34
},
{
"category": "Positive Notification",
"event": "open",
"result": 42
},
{
"category": "Referral",
"event": "delivered",
"result": 17
},
{
"category": "Positive Notification",
"event": "processed",
"result": 504
},
{
"category": "Referral",
"event": "processed",
"result": 18
},
{
"category": "Positive Notification",
"event": "delivered",
"result": 504
},
{
"category": "Negative Notification",
"event": "bounce",
"result": 16
},
{
"category": "Positive Notification",
"event": "bounce",
"result": 176
},
{
"category": "Referral",
"event": "open",
"result": 10
}
]
}
输出方式的问题取决于数据是否可用的天气,按数字访问对象可能会产生意想不到的功能。第二个问题是必须通过javascript操作,不能在服务器端操作。
我希望重新格式化 JSON,以便每个类别都是一个对象(目前有三个,但可能多达五个)在对象内汇总数据。例如:
{
"result": {
"Negative Notification" : [
{
"processed":34,
"delivered":34,
"bounces":16,
"opens":2
}
],
"Positive Notification" : [
{
"processed":504,
"delivered":504,
"bounces":176,
"opens":42
}
],
"Referral" : [
{
"processed":18,
"delivered":17,
"bounces":1,
"opens":10
}
]
}
}
我将如何解决这个问题?简单地循环遍历并命名对象并没有让我走到任何地方。