将JSON转换为特定的字符串格式

时间:2015-02-14 21:38:12

标签: javascript json

我从服务器获得以下json数据。

{"visits":[{"City":6,"Count":5},{"City":16,"Count":1},{"City":23,"Count":1},{"City":34,"Count":1}]}

我需要将其转换为以下格式:

{"1":"82700","2":"26480","3":"31530","4":"22820","5":"15550","6":"205790"}

我有以下代码,但没有成功:

       var cities = "{";

        for (var key in data.visits) {
            var val = data.visits[key];
            //Now you have your key and value which you 
            //can add to a collection that your plugin uses
            var obj = {};
            obj[val.City] = '' + val.Count;

            var code = '' + val.City;
            var count = '' + val.Count;

            cities += code + ':' + count + ',';
        }

        cities += "}";

我需要字符串表示中的整数,并且需要摆脱最后的,。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

试试这个

var data    = {"visits":[{"City":6,"Count":5},{"City":16,"Count":1},{"City":23,"Count":1},{"City":34,"Count":1}]};
var result = {};

for (var i = 0; i < data.visits.length; i++) {
  result[data.visits[i].City] = String(data.visits[i].Count);
}

Example

对象中的键始终转换为字符串,您不需要手动将其转换为字符串。如果您需要将所有对象转换为JSON字符串,则可以使用JSON.stringify(result);

答案 1 :(得分:1)

我如何理解你想用给定的json创建新的json.you可以解析它,在它上面循环运行,并创建一个新的json你想要的任何类型。 这是一个可以帮助你的链接。 http://www.w3docs.com/learn-javascript/working-with-json.html