Michael Ramos
Michael Ramos

Reputation: 5817

Json Parsing nested array

I have been referencing to this post Access / process (nested) objects, arrays or JSON, put have had no luck in figuring this out:

i have this JSON that I get from a http request: and in my app I need to asks the Posts object.

    { 
      "email" : "[email protected]", 
      "username" : "rambo",
      "fullname" : "Michael Stalone",
      "posts" : [
                 { "username" : "Bad Man",  
                   "comments" : 
                      [ 
                         { "com_user" : "michael", "com_post" : "good stuff" },
                         { "com_user" : "alex", "com_post" : "hell yes" }  
                      ]  
                  }, 
                  { "username" : "CheckerTats", 
                    "comments" : [ 
                          { "com_user" : "basky", "com_post" : "wow awesome" } 
                      ] 
                  }
                ]
      }

I get it fine and see everything as it should be. I also notice it returns and array object so i index the varriable i assign it to: var items = data[0]. console.log(data[0]) shows this:

{
 "email":"[email protected]",
 "username":"rambo",
  "fullname":"Michael Stalone",
  "posts":["[object Object]","[object Object]"]
}

So this is all good and dandy and realize I need to take it a step further and investigate data[0]['posts'][0] which shows to be:

[object Object]

I am now almost certain that this is the first post object. I would think that data[0]['posts'][0]['username'] would give me that particular user name. To make matters worse my dev environment is an iOS Apache Cordova app, so when I run console.log on it I am returned nothing.I have assigned this to variables, uses stringify, dot notation, and am still continuously not able to access this object. I need to do so to assign it to an angular scope variable.

EDIT:

A new log is now returning undefined:

 var items = dat[0]['posts'][0];
 console.log(items['username']); // undefined

Upvotes: 1

Views: 9864

Answers (2)

Madhura KM
Madhura KM

Reputation: 140

if variable dat holds your json object. Then you can try below code to access username in your json:

dat.posts[0].username

Upvotes: 0

Andras
Andras

Reputation: 3055

look closely at data[0]: posts contains an array of two strings that say "[object Object]", not two objects. How are you parsing the json?

oh, and your syntax is correct for extracting the username from the nested objects

Upvotes: 3

Related Questions