1

I have the JSON result:

[ { "_id" : { "$oid" : "5237d438e4b07666dcca4896"} , 
    "username" : "user" , "password" : "asdf"} ]

That is returned from a GET request. I am trying to decode this result, I can't seem to access the username or password keys. This is what I tried:

$obj = json_decode($result[0]);
echo $obj->username;

However it seems to return the entire result(the array) every time.

1
  • The result is the same whether I use the 0 index or not. Commented Sep 17, 2013 at 6:13

4 Answers 4

2

If you add a second parameter boolan true to json_decode like

$obj = json_decode($result[0], true);

Then you will get associative array instead of an object.

and can access values through keys like

echo $obj['username'];
Sign up to request clarification or add additional context in comments.

3 Comments

He wants to access values direct with their keys like username and password.
As I can see from his tryings, he wants to access them as objects, not arrays
I just gave a solution to access values with the keys directly.
1
$result = '[ { "_id" : { "$oid" : "5237d438e4b07666dcca4896"} , 
    "username" : "user" , "password" : "asdf"} ]';
$obj = json_decode($result);
var_dump($obj);
/**
 * Array containg object. So now $obj is just an array
 * 
array (size=1)
  0 => 
    object(stdClass)[1]
      public '_id' => 
        object(stdClass)[2]
          public '$oid' => string '5237d438e4b07666dcca4896' (length=24)
      public 'username' => string 'user' (length=4)
      public 'password' => string 'asdf' (length=4)
 * 
 * 
 * Key 0 contains object properties _id; username; password
 * 

 */

echo $obj[0]->username;  // user

Comments

1

Try to use this:

$json = json_decode($result);
echo $json[0]->username;

Full example:

<?php
header('Content-Type: text/plain; charset=utf-8');

$result = '[ { "_id" : { "$oid" : "5237d438e4b07666dcca4896"} , 
    "username" : "user" , "password" : "asdf"} ]';

$json = json_decode($result);
echo $json[0]->username;
?>

Result:

user

4 Comments

You cant access to object with 0 index.
@Bora globally $obj is an array containing objects
@Bora fixed to be more understandable.
I missed the [] brackets sorry ;)
0

yes you are right json_decode function returns an array. You need to fetch value from that array. In above case you need to fetch username like below:

echo $json_encode[0]->username;;

depends upon your json.

You can refer this link:

1 Comment

It returns an array, but username is not an array key

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.