Search code examples
phpwordpresspluginswordpress-rest-api

How to return valid JSON array by WordPress REST API .. Not JSON object?


I'm working on WordPress site and been asked to supply mobile developer by JSON API data for a slider. I have to add the slider data like images and titles etc. I've found a plugin which serve an end point called MetaSlider. I've did required things and the response was perfect. but the developer replied by this:

"I am not talking about data. It should be a valid JSON array. Plz have a look at data structure of response object

"0": {
"id": 2669,
"title": "New Slideshow",

This is not valid json. It should be a JSON Array like this
[ {
"id": 2669,
"title": "New Slideshow","

Does any one have a clue?

I looked for a plugin that can do the job but I didn't find any.


Solution

  • I was experiencing the same issue.

    If your array is as result of using array_map, wrap your response with array_values($data).

    This is the function I have as a callback for register_rest_route;

      public function terms_ep( $request ) {
    
        $terms = get_terms('my_taxonomy', []);
    
        $data = array_map(function($t){
          return [
            'id' =>  $t->term_id,
            'name' => $t->name
          ];
        }, $terms);
    
    
        return rest_ensure_response( array_values($data) );
    
      }
    

    With array_values it produces a nice json array:

    [
        {
            "id": 13,
            "name": "A"
        },
        {
            "id": 12,
            "name": "B"
        }
    ]
    

    Without the response is this object response:

    {
        "0": {
            "id": 13,
            "name": "A"
        },
        "2": {
            "id": 12,
            "name": "B"
        }
    }