在AngluarJs或JavaScript中将JSON字符串转换为Array

时间:2015-07-15 14:44:59

标签: javascript json angularjs

在AngularJS中将JSON字符串转换为数组

示例JSON字符串:

"{"Madinaguda":1,"Basheer Bagh":1}"

需求输出如下:

var reuslt= [{ LocationsName : Madinaguda ,LocationCount:1 },
            { LocationsName : Basheer Bagh , LocationCount :1}];

2 个答案:

答案 0 :(得分:2)

这是一个非常简单的解决方案:

var jsonStr = '{"Madinaguda":1,"Basheer Bagh":1}',
    json = JSON.parse(jsonStr),
    result = [];

for (var key in json) {
    if(json.hasOwnProperty(key) ) {
        result.push({
            LocationsName: key,
            LocationCount: json[key]
        });
    }
}

// result is what you want

答案 1 :(得分:1)

这应该这样做:

function parseIt(jsonString) {
    "use strict";        
    var result = [], parsedObject, key;

    parsedObject= JSON.parse(jsonString);
    for(key in parsedObject) {
        if(parsedObject.hasOwnProperty(key) ) {
            result.push({LocationsName : key, LocationCount : parsedObject[key]});
        }
     }
     return result;     
}

继承人Fiddle