我是json的新手。我有点麻烦将json从一种格式转换为另一种格式。 这是我要转换的json。
{
"message": "Successfully Advisor data has been fetched.",
"success": true,
"data": {
"dataHeaders": ["Carrier","B2B", "EM"],
"dataArray": {
"DHL": ["DHL", "45", "5","5"],
"Fedex": ["Fedex","40", "7","6"],
"UPS" : ["UPS","30", "10","3"],
"TNT" : ["TNT","30", "10","3"],
}
}
}
我要求将json转换为此格式。
[
{
"key":"Carrier",
"values":[
{
"x":"DHL",
"y":45
},
{
"x":"Fedex",
"y":40
},
{
"x":"UPS",
"y":30
},
{
"x":"TNT",
"y":35
}
]
},
{
"key":"B2B",
"values":[
{
"x":"DHL",
"y":5
},
{
"x":"Fedex",
"y":7
},
{
"x":"UPS",
"y":10
},
{
"x":"TNT",
"y":5
}
]
},
{
"key":"EM",
"values":[
{
"x":"DHL",
"y":5
},
{
"x":"Fedex",
"y":6
},
{
"x":"UPS",
"y":3
},
{
"x":"TNT",
"y":5
}
]
}
]
如何使用jquery执行此操作?
答案 0 :(得分:0)
使用var obj = jQuery.parseJSON()来解析输入字符串。您可以通过obj。[FIELDNAME]访问这些字段并构建输出字符串。
答案 1 :(得分:0)
你可以从这样的事情开始:
$.each(a.data.dataArray,function(){
//use this[] with the index
});
$.each(a.data.dataHeaders,function(){
//use this for the headers values
});
并构造输出对象。
答案 2 :(得分:0)
因为我在午餐期间有一点空闲时间,所以给了你一个机会,这应该让你去:
var before = {
"message": "Successfully Advisor data has been fetched.",
"success": true,
"data": {
"dataHeaders": ["Carrier","B2B", "EM"],
"dataArray": {
"DHL": ["DHL", "45", "5","5"],
"Fedex": ["Fedex","40", "7","6"],
"UPS" : ["UPS","30", "10","3"],
"TNT" : ["TNT","30", "10","3"],
}
}
};
parseData = function (jsonData) {
var result = [];
jsonData.data.dataHeaders.forEach(function (carrier, indexHeader) {
var el = {}
el.key = carrier;
el.values = [];
// shortcut
dataArray = jsonData.data.dataArray;
// generate sub elements
for (arr in dataArray) {
// generate element
subEl = {};
subEl.x = arr;
subEl.y = dataArray[arr][indexHeader + 1];
// add to array
el.values.push(subEl);
}
// add el to result
result.push(el);
});
return result;
}
var after = parseData(before);