如何构建嵌套的JSON对象?

时间:2013-03-26 02:22:15

标签: java javascript json web-applications servlets

我是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,最好的方法是什么?

谢谢, 杰

2 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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);