-1

我是 JSON 新手,并且有一个 Java servlet,它提供以下 JSON 输出:

{
     "35808": "Huntsville, Alabama",
     "94203": "Sacramento, California",
     "33054": "Miami, Florida",
     "32801": "Orlando, Florida",
     "30301": "Atlanta, Georgia",
     "78717": "Austin, Texas"
}

通过 Javascript 检索 JSON 后,我想创建一个按状态分组的嵌套 JSON,结果应该是:

 {
     "A": {
         "35808": "Huntsville, Alabama"
     },
     "C": {
         "94203": "Sacramento, California"
     },
     "F": {
         "33054": "Miami, Florida",
         "32801": "Orlando, Florida"
     },
     "G": {
         "30301": "Atlanta, Georgia"
     },
     "T": {
         "78717": "Austin, Texas"
     }
}

最好使用 Javascript 来完成此任务的最佳方法是什么?或者如果使用 Java,最好的方法是什么?

谢谢,杰

4

2 回答 2

0

这应该这样做:

var parsedJSON = …;
var byState = {};
for (var prop in parsedJSON) {
    var address = parsedJSON[prop];
    var state = address.split(",")[1] || "";
    var stateKey = state.charAt(0);
    if (! (stateKey in byState))
        byState[stateKey] = {};
    byState[stateKey][prop] = address;
}
console.log(JSON.stringify(byState, null, 4));
于 2013-03-26T02:32:34.370 回答
0

这假设状态是排序的。 http://jsfiddle.net/N23SL/

var originalJson = {
     "35808": "Huntsville, Alabama",
     "94203": "Sacramento, California",
     "33054": "Miami, Florida",
     "32801": "Orlando, Florida",
     "30301": "Atlanta, Georgia",
     "78717": "Austin, Texas"
}


var groupMe = function(originalJson)
{
    var grouped = {};
    // loop over each property
    for(var key in originalJson)
    {
        var value = originalJson[key];
        var state=value.split(", ")[1];
        var stateLetter = state[0];

        var letterGroup = grouped[stateLetter];
        if(typeof letterGroup === 'undefined')
        {
            letterGroup = {};
            grouped[stateLetter] = letterGroup;
        }

        letterGroup[key] = value;
    }

    return grouped;

};

var groupedJson = groupMe(originalJson);

console.log(groupedJson);
于 2013-03-26T02:36:35.313 回答