-1

我是 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 做到这一点?

4

3 回答 3

0

使用var obj = jQuery.parseJSON()解析您的输入字符串。您可以通过 obj.[FIELDNAME] 访问字段并构建您的输出字符串。

于 2013-08-07T09:53:20.153 回答
0

你可以从这样的事情开始:

$.each(a.data.dataArray,function(){
   //use this[] with the index
});

$.each(a.data.dataHeaders,function(){
  //use this for the headers values
});

并构造您的输出对象。

于 2013-08-07T09:58:38.050 回答
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);

JSFiddle

于 2013-08-07T10:39:06.887 回答