I am having trouble accessing information in a json-Array that I retrieved using php's json_decode
function.
the json-file looks as follows:
{"code":0,"message":"Okay","model":{"results":[{"message":"Okay","balance":0,"openPositions":[[],[]],"firstDepositDate":XXX,"currencySign":"€","email":"[email protected]","code":0}]},"result":"success"}
I used the following php code to get the contents:
$json = file_get_contents($json_url);
$data = json_decode($json,true);
echo '<pre>' . print_r($json, true) . '</pre>';
The result print_r displays looks just like what I expect and looks like the json.
However, I cannot figure out to access the variables. Whenever I try something like
$test = $json['model']['results']['balance'];
the script throws an error, which I can't identify. I already figured out if I access the $json
variable like so:
$test = $json[n]; // returns the nth character, e.g. n = 0 $test = "{", n = 2 $test = "c"
The script also did not throw an error if I tried accessing the variable like so:
$test = $json['code']; // returns "{"
Can someone help me figure out how to navigate this array?
Thanks!
3 Answers 3
The results
key is a true array, not an unordered map (key/value). Additionally, you should be accessing the decoded $data
, not the $json
string.
This should work for you:
$test = $data['model']['results'][0]['balance'];
This is what should have tipped you off:
{"results":[{"message"
^ ^
| |
| \-- Start of an array
|
\-- Start of an object
5 Comments
$data
, not the $json
string.->
instead like an array?json_decode
defaults to parsing to an object, but if the second parameter is true
to parses to an array.You recieve an error similar to Cannot use object of type stdClass as array in (...)
right?
json_decode returns an object of the type stdClass
which is the only object in php (as far as I know) which properties cannot be accessed like an array. You will have to access them as follows:
$json = '{"code":0,"message":"Okay","model":{"results":[{"message":"Okay","balance":0,"openPositions":[[],[]],"firstDepositDate":"XX","currencySign":"€","email":"[email protected]","code":0}]},"result":"success"}';
$obj = json_decode($json);
var_dump($obj->message); //works
var_dump($obj["message"]); //throws exception
Comments
There is an error in the JSON array. "firstDepositDate": XXX is not a valid value. Should be a string "XXX".
Also you are trying to the wrong variable. The decoded data should be a PHP array. In this case $data['code'] instead of $json['code']
$json
contains a string (JSON itself), not an array (result of decoding JSON). Use$data
instead. Also, as noted in the answer given,$data['model']['results']
is a regular array; to access its elements, use$data['model']['results'][0]['message']
syntax.