将JSON字符串转换为另一种格式

时间:2017-02-07 20:12:05

标签: javascript json

我有一个以下格式的json,我想将这个JSON转换为问题末尾提到的格式。我想只使用javascript来进行这种转换,而不是像Gson或服务端Java代码那样的任何其他工具。请告诉我这是如何实现的。

 [{
    "innNumber": {
        "id": "0111",
        "idAsLong": 111,
        "idWithoutZero": "111"
    },
    "nightlyRates": [{
        "date": "2017-02-09",
        "nightlyRate": {
            "amount": 155.85,
            "currencyCode": "CAD"
        },
        "points": 0
    }]
}, {
    "innNumber": {
        "id": "0111",
        "idAsLong": 111,
        "idWithoutZero": "111"
    },
    "nightlyRates": [{
        "date": "2017-02-09",
        "nightlyRate": {
            "amount": 155.85,
            "currencyCode": "CAD"
        },
        "points": 0
    }]

}]

JSON响应将采用以下所需格式。

    [{"hotelRoomRate":{
    "innNumber": {
        "id": "0111",
        "idAsLong": 111,
        "idWithoutZero": "111"
    },
    "nightlyRates": [{
        "date": "2017-02-09",
        "nightlyRate": {
            "amount": 155.85,
            "currencyCode": "CAD"
        },
        "points": 0
    }]

  } 
}, 
{"hotelRoomRate":
  {
    "innNumber": {
        "id": "0111",
        "idAsLong": 111,
        "idWithoutZero": "111"
    },
    "nightlyRates": [{
        "date": "2017-02-09",
        "nightlyRate": {
            "amount": 155.85,
            "currencyCode": "CAD"
        },
        "points": 0
    }]

}   
}]

2 个答案:

答案 0 :(得分:3)

一个简单的map()会做到这一点

var res = data.map(function(item){
   return { hotelRoomRate : item};
});

答案 1 :(得分:0)

我就是这样做的......

    var JsonData = [{
        "innNumber": {
            "id": "0111",
            "idAsLong": 111,
            "idWithoutZero": "111"
        },
        "nightlyRates": [{
            "date": "2017-02-09",
            "nightlyRate": {
                "amount": 155.85,
                "currencyCode": "CAD"
            },
            "points": 0
        }]
    }, {
        "innNumber": {
            "id": "0111",
            "idAsLong": 111,
            "idWithoutZero": "111"
        },
        "nightlyRates": [{
            "date": "2017-02-09",
            "nightlyRate": {
                "amount": 155.85,
                "currencyCode": "CAD"
            },
            "points": 0
        }]

    }]

var newFormat = [];

for(var i =0; i < JsonData.length; i ++){
   newFormat.push({"hotelRoomRate" : JsonData[i]})
}

console.log(newFormat)

希望这有帮助