0

我收到了一个 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"}]

任何指针或代码都非常感谢

4

2 回答 2

1

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

不过考虑一下:

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);
于 2012-07-07T07:52:52.237 回答
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"]);
}
于 2012-07-07T07:47:30.257 回答