David McClave
David McClave

Reputation: 167

My Json isn't parsing properly

simple script gets a json file, strips out extraneous headers, and tried to access a single key/value with no luck. anyone?

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

The results are:

original response =

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 is:

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

The print_r of the trimmed json prints:

1 using "$obj->{'target_id'}" to get name give me this:

Upvotes: 0

Views: 77

Answers (2)

Samuel
Samuel

Reputation: 2156

try this:

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

Upvotes: 1

David McClave
David McClave

Reputation: 167

Simple solution: using "true" in the json_decode converts the object to an associative array. Items inside are then accessed at $Array[$key][key].

Upvotes: 0

Related Questions