0

I have a simple JSON file:

{
"json.transactionDetails":{
 "transactionDate":1266518024,
 "transactionType":"bought",
 "userDescription":"reimbursement",
 "transactionDescription":"Bought 10 AAPL @200",
 "quantity":10,
 "amount":"2010.00",
 "price":"200.00",
 "commission":"10.00",
}
}

Then a PHP file getting the JSON:

$t_detail = file_get_contents("details.json");
$transaction_detail = json_decode($t_detail);
$tr_detail = $transaction_detail->json.transactionDetails; //this is my issue

$transaction_type = $tr_detail->transactionType;
$user_description = $tr_detail->userDescription;

How do I parse the "json.transactionDetails"? The period is causing my script to fail. If I remove the "json." from both scripts everything works fine. Is there a way to skip over the first object in the tree or what? I can't change the way the JSON is outputted because it's coming from and external API.

Chad Priddle
  • 650
  • 2
  • 15
  • 32
  • 2
    the `.` is the concatenation operator in php. You would need to specify the key as `$transaction_detail->{"json.transactionDetails"}` – Jonathan Kuhn Oct 20 '14 at 18:34
  • 1
    I'd suggest doing `json_decode($t_detail, TRUE);`. This will make PHP give you an array instead of an object, then you can do `$transaction_detail['json.transactionDetails']`. – gen_Eric Oct 20 '14 at 18:35

1 Answers1

1

try to

$transaction_detail = json_decode($t_detail,true);
$tr_detail = $transaction_detail['json.transactionDetails'];

When you make 2 nd parameter of json_decode to true , it will parse the json as an array so you can simply get the values using array['key'] syntax

or you can

$transaction_detail = json_decode($t_detail);
$tr_detail = $transaction_detail->{"json.transactionDetails"};
Kanishka Panamaldeniya
  • 17,302
  • 31
  • 123
  • 193