Back

Json response removes key in array :(


Hi

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:

["promo\\1\\images\\2.jpg","promo\\1\\images\\20150927_100644.jpg","promo\\1\\main\\1.jpg","promo\\3\\images\\2.jpg","promo\\3\\images\\20150927_100644.jpg","promo\\3\\main\\1.jpg","promo\\4\\images\\2.jpg","promo\\4\\main\\1.jpg"]

I cannot find anything to solve this.

Thanks

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

@Ognjen

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