api - how to create JSON array [] for REST response?

admin2025-01-07  9

I am trying to create a REST response for a self-developed API in WordPress. The current code is

    $response = array();

    $response[] = array(
        'version' => '1.0',
        'user' => array(
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'email' => $user->user_email,
            'id' => $user->ID,
        ),
    );

return rest_ensure_response( $response );

Which returns (i am using a user object)

[
{
"version": "1.0",
"user": {
    "first_name": "Test",
    "last_name": "User",
    "email": "[email protected]",
    "id": 19
}
}
]

However i need it in this form

[
  {
"version": "1.0",
"user": [
    {
        "first_name": "Test",
        "last_name": "User",
        "email": "[email protected]",
        "id": 19,
    }
    ]
  }
]

So the challenge here is how to get the [] around the "user"?

This is more likely a general questions as im unable to add the "[" and "]" manually to the response array

Best, Thomas

I am trying to create a REST response for a self-developed API in WordPress. The current code is

    $response = array();

    $response[] = array(
        'version' => '1.0',
        'user' => array(
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'email' => $user->user_email,
            'id' => $user->ID,
        ),
    );

return rest_ensure_response( $response );

Which returns (i am using a user object)

[
{
"version": "1.0",
"user": {
    "first_name": "Test",
    "last_name": "User",
    "email": "[email protected]",
    "id": 19
}
}
]

However i need it in this form

[
  {
"version": "1.0",
"user": [
    {
        "first_name": "Test",
        "last_name": "User",
        "email": "[email protected]",
        "id": 19,
    }
    ]
  }
]

So the challenge here is how to get the [] around the "user"?

This is more likely a general questions as im unable to add the "[" and "]" manually to the response array

Best, Thomas

Share Improve this question asked Nov 17, 2020 at 8:46 Thomy1985Thomy1985 11 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 1

Just use another array() inside user array()

$response = array();

$response[] = array(
    'version' => '1.0',
    'user' => array(
        array(
            'first_name' => 'Razon',
            'last_name' => 'komar pal',
            'email' => '[email protected]',
            'id' => 10,
        )
    ),
);

return rest_ensure_response($response);

It will output like:

[
    {
        "version": "1.0",
        "user": [
            {
                "first_name": "Razon",
                "last_name": "komar pal",
                "email": "[email protected]",
                "id": 10
            }
        ]
    }
]

Hope this will work for you :)

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736265109a1020.html

最新回复(0)