Magento – Convert model collection to json_encode

collection;jsonmagento2modelperformance

Currently I'm converting my collection data to json_encode like this:

$collections = $this->modelFactory->create()->getCollection()
                   ->addFieldToFilter('status','1');
$result = array();
foreach($collections as $collection){
  $result[] = $collection->getData();
}
return json_encode($result);

The problem is I need to loop for each collection to get the array data so that I can put it inside json_encode function, is there a way I can convert the collection result to json_encode without looping?

Best Answer

Try this:

$result = $collections->toArray();

return json_encode($result);

or

$result = $collections->getData();
return json_encode($result);
Related Topic