user2423476
user2423476

Reputation: 2275

How would I parse this json?

I've been having issues trying to parse this json data.
I tried to do this to return the name but its not working:

 foreach(json_decode($test) as $item){  
 $name= $item->users->name;}

This is the json code:

 {
  "users":[
 {
 "id":"dsfdfsd",
 "id_str":"dsfsdf",
 "name":"Davy",
 "screen_name":"Davy232",
 "location":"Colorado"
 },
{
 "id":"wer",
 "id_str":"wer",
 "name":"Sarah",
 "screen_name":"Davy232",
 "location":"LA"
  },
 {
 "id":"fdf",
 "id_str":"fdf",
 "name":"James",
 "screen_name":"James374",
 "location":"Vegas"
  }
]
}

Upvotes: 2

Views: 51

Answers (1)

That is because the JSON is invalid , Here's the proper fixed JSON

Fixed JSON Data

{
   "users":[
  {
     "id":"dsfdfsd",
     "id_str":"dsfsdf",
     "name":"Davy",
     "screen_name":"Davy232",
     "location":"Colorado"
  }
]
}

What were the problems ?

  • You did not surround dsfdfsd with doubles quotes.
  • There was an extra comma after Colorado
  • The braces were not properly balanced.

Also, your foreach should be like this..

foreach(json_decode($test) as $item){  
 echo $item[0]->name;
 }

Working Demo - Part 1 Working Demo - Part 2

Upvotes: 2

Related Questions