我的Json;t解析正确


My Json isn't parsing properly

简单脚本获取一个json文件,去掉多余的头,并尝试访问单个键/值,但没有成功。任何人

代码

$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"}

我修剪的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'}"获取名称,给我这个:

试试这个:

$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>";

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