Luca Reghellin
Luca Reghellin

Reputation: 8125

How to properly format a WP_REST_Response in json and get arrays instead of objects?

I'm building a very small app in wordpress and need to get json data via ajax. I'm facing a strange (at least to me) problem. My original data log is like this (please pay attention to items and children > they're arrays):

object(stdClass)#6740 (2) {
  ["type"]=>
  string(5) "areas"
  ["items"]=>
  array(1) {
    [92]=>
    object(stdClass)#6742 (10) {
      ["term_id"]=>
      int(92)
      ["name"]=>
      string(6) "Italia"
      ["slug"]=>
      string(6) "italia"
      ["term_taxonomy_id"]=>
      int(92)
      ["taxonomy"]=>
      string(12) "dealer_areas"
      ["description"]=>
      string(0) ""
      ["parent"]=>
      int(82)
      ["count"]=>
      int(1)
      ["term_order"]=>
      float(0.1)
      ["children"]=>
      array(1) {
        [126]=>
        object(stdClass)#6741 (10) {
          ["term_id"]=>
          int(126)
          ["name"]=>
          string(8) "Sardegna"
          ["slug"]=>
          string(8) "sardegna"
          ["term_taxonomy_id"]=>
          int(126)
          ["taxonomy"]=>
          string(12) "dealer_areas"
          ["description"]=>
          string(0) ""
          ["parent"]=>
          int(92)
          ["count"]=>
          int(1)
          ["term_order"]=>
          float(0.10003)
          ["children"]=>
          array(0) {
          }
        }
      }
    }
  }
}

If I pass it directly to WP_REST_Response and then to js as a json response (return new WP_REST_Response($response_obj)), I get a log like this:

enter image description here

As you can see, it's not exactly json... There are getter/setter methods..

OK, then I pass the value json encoded (return new WP_REST_Response(json_encode($response_obj))) and parse in javascript via JSON.parse(). I get this:

enter image description here

or this (another example with more than 1 obj)

enter image description here

As you can see, I get json, but even if original items data was an array, now I get an object. How to preserve the original array type?

Upvotes: 0

Views: 3250

Answers (1)

Luca Reghellin
Luca Reghellin

Reputation: 8125

My own answer is:

  1. It's not a WP_REST_Response issue.
  2. It's not a json_decode issue
  3. The issue is the data format and the way javascript reads arrays

In short: it's not possible to convert php non-consecutive indexed arrays to javascript arrays, since javascript wants consecutive integers keys. In all the other cases, javascript reads as associative arrays or objects (which are essentially the same). Therefore, json conversion of php non-consecutive indexed arrays will always output objects.

Upvotes: 2

Related Questions