0

In my API, I use resources for all the endpoints. For the most part, I'm returning arrays of data and they work just fine. However, for a couple of endpoints, I have some data that looks something like the following:

[
  "123" => ["total"=>123, "average"=>12.7],
  "456" => ["other"=>"data"],
]

where the keys are the ids for other objects already provided by the API. However, when I send that data to the resource, the response essentially turns the data into a straight array, so the JSON representation looks as follows:

[
  ["total": 123, "average": 12.7],
  ["other": "data"]
]

I'm thinking this is more of an issue issue with json_encode underneath the hood, but is there anything I can do in the toArray() method to keep the keys when they're numeric strings? The only things that have worked for me so far are to prepend a non-numeric string key (e.g. dummy to the object), or to add a letter to each key (e.g. a123, a456, etc.).

1
  • Check accepted answer here. Commented Oct 2, 2018 at 17:50

2 Answers 2

3

A bit late but for anyone having the same issue, you can do this right now:

class MyCustomResource extends JsonResource
{
    /**
     * Keep resource keys as they are.
     * If set to `false` (default), the JsonResource's filter will flatten the array/collection without numerical keys
     *
     * @var boolean
     */
    protected $preserveKeys = true;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could try sending your response from the controller back with Laravel's integrated JSON converter:

$toJson = [
      "123" => ["total"=>123, "average"=>12.7],
      "456" => ["other"=>"data"],
 ];
 return response()->json($toJson);

This will succesfully return a JSON looking like this:

{
  '123': {
    total: 123,
    average: 12.7,
  },
  '456': {
    other: "data",
  },
}

1 Comment

That's true...I guess I should have been more explicit...I've extended the JsonResource to send some common meta fields in addition to the data, so for sake of consistency, I'd like to use a resource. However, manually doing it as you have indicated is probably the most readable way to do it.

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.