我的Json没有正确解析

时间:2013-12-16 10:33:12

标签: php json

简单脚本获取一个json文件,删除多余的标题,并尝试访问单个键/值,没有运气。任何人吗?

CODE

$postURL = "http://case42.com/ogle/GetTarget.php?targetid=32feaf056b8c46e4a6f5500b6289cf59";
$json = file_get_contents($postURL);
echo "original response = <P>" . $json ."<HR>";
$strip = "target_record";
$mypos = strpos($json, $strip);
$json = substr($json,$mypos+15);
echo "My Trimmed json is: <P>" . $json."<HR>";
$obj = json_decode($json, true);
echo "<P>The print _ r of the trimmed json prints:<P> " . print_r ($json);
echo "<HR>";

echo "using \"\$obj->{'target_id'}\" to get name give me this: ".$obj->{'name'}."<HR>";

结果如下:

原始回复=

GET
d41d8cd98f00b204e9800998ecf8427e

Mon, 16 Dec 2013 10:36:23 GMT
/targets/32feaf056b8c46e4a6f5500b6289cf59{"target_record":{"target_id":"32feaf056b8c46e4a6f5500b6289cf59","name":"Francesca Grace","width":300.0,"active_flag":true,"tracking_rating":5,"reco_rating":""},"status":"success","result_code":"Success","transaction_id":"23029749e4984e2d92dbfb5ff44f8834"}

My Trimmed json是:

{"target_record":{"target_id":"32feaf056b8c46e4a6f5500b6289cf59","name":"Francesca Grace","width":300.0,"active_flag":true,"tracking_rating":5,"reco_rating":""},"status":"success","result_code":"Success","transaction_id":"b427cb1f89544b4c85332ca0ad174848"}

修剪过的json的print_r打印:

1 使用"$obj->{'target_id'}"获取名称给我这个:

2 个答案:

答案 0 :(得分:1)

试试这个:

$postURL = "http://case42.com/ogle/GetTarget.php?targetid=32feaf056b8c46e4a6f5500b6289cf59";
$json = file_get_contents($postURL);
echo "original response = <P>" . $json ."<HR>";
$strip = "target_record";
$mypos = strpos($json, $strip);
$json = substr($json,$mypos-2);
echo "My Trimmed json is: <P>" . $json."<HR>";
$obj = json_decode($json, true);
echo "<P>The print _ r of the trimmed json prints:<P> " . print_r ($json);
echo "<HR>";

echo "using \"\$obj->{'target_id'}\" to get name give me this: ".$obj['tagret_record']['name']."<HR>";

答案 1 :(得分:0)

简单解决方案:在json_decode中使用“true”将对象转换为关联数组。然后在$ Array [$ key] [key]访问里面的项目。