0

I am using the codeigniter rest by phil sturgeon.

I want to return a JSON object that contains another JSON object within.

My code looks like this

function volunteer_get()
    {
        if(!$this->get('id'))
        {
            $this->response(NULL, 400);
        }

        $this->load->model('user/users_model');

        $user = $this->users_model->get( $this->get('id') );
        $address = $this->address_model->getAddress( $this->get('id') );

        $user->address = $address;

        $userJson = json_encode($user);
        var_dump($userJson);

        /*if($user && $user->auth_level == 1)
        {
            $this->response($userJson, 200); // 200 being the HTTP response code
        }
        else
        {
            $this->response(NULL, 404);
        }*/
    }

It is not showing any result... If i do this without adding the php object in the other php object, it shows me the json!

D:\wamp\www\codeigniter\application\controllers\api\Users.php:37:string '{"user_id":"1","username":"abc","email":"abc","auth_level":"1","banned":null,"passwd":"abcdefg","passwd_recovery_code":"abcdefg","passwd_recovery_date":"2017-06-12 18:50:31","passwd_modified_at":"2016-11-18 21:20:30","last_login":"2017-08-30 15:10:36","created_at":"2016-09-02 12:01:46","modified_at":"2017-08-30 15:22:45","first_name":"aze","family_name":"'... (length=1354)
1
  • Is $user an array or an object? Try echo gettype($user); and let me know what it shows. Commented Oct 5, 2017 at 16:35

1 Answer 1

2

In general, you need to check whether you got a JSON object (usually a PHP dictionary or object) or a JSON representation (a string).

You can not add a string to another string. And if you add a string to a dictionary or object, it won't be properly encoded as a JSON sub-object because it is, well, a string.

So if you have a representation, you have to decode it first:

// Here, $dataOne is a string, and $dataTwo is too.
// we decode to array rather than to object (see manual for json_encode)

$dataOneJSON = json_decode($dataOne, true);

$dataTwoJSON = json_decode($dataTwo, true);

$dataOneJSON['two'] = $dataTwoJSON;

$result = json_encode($dataOneJSON);

$this->response($result, 200);
Sign up to request clarification or add additional context in comments.

Comments

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.