Json response removes key in array :(


dd my array looks like this:

array:8 [▼
  0 => "promo\1\images\2.jpg"
  1 => "promo\1\images\20150927_100644.jpg"
  2 => "promo\1\main\1.jpg"
  3 => "promo\3\images\2.jpg"
  4 => "promo\3\images\20150927_100644.jpg"
  5 => "promo\3\main\1.jpg"
  6 => "promo\4\images\2.jpg"
  7 => "promo\4\main\1.jpg"

When i do this

return response()->json($path);

The key is lost and the output looks like this:


I cannot find anything to solve this.


LaurentMeganck replied 2 years ago Solution

The keys aren't lost. Keys will still start at 0 for the json output

Ognjen replied 2 years ago

As fourth parameter json method accepts json_encode options. You can use JSON_FORCE_OBJECT to encode array as object.

echo response()->json(['one', 'two'], 200, [], , JSON_FORCE_OBJECT );
 // {"0":"one","1":"two"}
LaurentMeganck replied 2 years ago


Why would you force the JSON method to encode an array as an object? Unless you want to pass an associative array to javascript, keep your variable types consistent.

Sign in to participate in this thread!

We'd like to thank these amazing companies for supporting us