JSON and oembed plugin

I am trying to add the embed plugin output to the JSON representation of a page to use it with AJAX. It works well with all fields except the embed. I guess the idea is a bit naive that this could work but this the current code of my default.json.php.


header('Content-type: application/json; charset=utf-8');
$image = $page->coverimage()->toFile();

$data = [
  'layout' => $page->layout()->value(),
  'title' => $page->title()->value(),
  'text'  => $page->text()->kirbytext()->value(),
  'media' => $page->mediaembed()->embed()

if($image) {
  $data['image'] = $image->url();

echo json_encode($data);

On the javascript side I load it via AJAX, which works well with standard fields, except the the embed ‘media’ => $page->mediaembed()->embed() which adds a value [Object object] to JSON.

Is there a way / does it make sense at all to add embeds to the JSON representation?

Any help appreciated.

You can probably convert it from an object to array with
i.e. 'media' => $page->mediaembed()->embed()->toArray()

Thanks Toby, unfortunately it doesn´t work and I get an error.