将json对象转换为json对象数组

时间:2012-07-07 07:36:03

标签: javascript jquery

我收到了一个json片段,其中包含以下行(字符串转换为json对象)

"profile":{"id":"billg","name":"Bill Gates","countryCode":"US"}

现在用户添加了一个配置文件,我需要将配置文件对象转换为配置文件对象数组。

"profile":[{"id":"billg","name":"Bill Gates","countryCode":"US"},{"id":"steve","name":"Steve Jobs","countryCode":"US"}]

非常感谢任何指针或代码

2 个答案:

答案 0 :(得分:1)

如果你展示一些你的代码真的很棒:我们基本上不知道这个json字符串的来源是什么(JSON = JavaScript Object Notation,所以'JSON对象'是一个重言式),我们不知道知道如何创建第二个配置文件。

考虑一下,但是:

var jsonData = '{"profile":{"id":"billg","name":"Bill Gates","countryCode":"US"}}';
var data     = JSON.parse(jsonData); // it's an object now...
var profile  = data.profile;         // storing another object as a value of `.profile` property
var anotherProfile = {"id":"steve","name":"Steve Jobs","countryCode":"US"};
if (! profile[0]) { // checking whether it's an array or not
   // it's not, so we should make an array, adding another profile as well
   data.profile = [data.profile, anotherProfile]; 
}
else { // but if it was, it'd be enough just to push anotherProfile into the end of it
   data.profile.push(anotherProfile);
}
console.log(data);

答案 1 :(得分:0)

Try This: 


   var obj = jQuery.parseJSON('"profile":[{"id":"billg","name":"Bill Gates","countryCode":"US"},{"id":"steve","name":"Steve Jobs","countryCode":"US"}]');

    var a = obj.profile;

    var jsonArrObj = $.parseJSON('[' + a + ']');

您可以像这样访问数组中的名称:

for (i in jsonArrObj)
{
alert(jsonArrObj[i]["name"]);
}