我怎么解析这个json?

时间:2014-04-20 02:10:51

标签: php json

我一直在尝试解析这个json数据时遇到问题 我试图这样做以返回名称,但它不起作用:

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

这是json代码:

 {
  "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"
  }
]
}

1 个答案:

答案 0 :(得分:2)

那是因为JSON无效,这是正确的固定JSON

修正了JSON数据

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

有什么问题?

  • 你没有用双打引号包围dsfdfsd
  • Colorado
  • 之后有一个额外的逗号
  • 牙箍没有得到适当的平衡。

此外,您的foreach应该是这样的..

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

Working Demo - Part 1 Working Demo - Part 2