0

I had received a json snippet, which has the following lines (string converted to json object)

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

now user adds one more profile, i need to convert profile object to an array of profile objects.

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

Any pointers or code is highly appreciated

2
  • 4
    Pointer #1) Try something first. Commented Jul 7, 2012 at 7:38
  • whathaveyoutried.com Commented Jul 7, 2012 at 7:41

2 Answers 2

1

It would be really great if you show some code of yours: we basically don't know what's the source of this json string (JSON = JavaScript Object Notation, so 'JSON object' is a tautology), and we don't know how is the second profile created.

Consider this, though:

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);
Sign up to request clarification or add additional context in comments.

Comments

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 + ']');

You can access names in array like this :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.