Views JSON entity reference fields I have a page content type with fields Title, Body and Blocks field collection with fields Title and URL.

It might be field collection, paragraphs or entity reference, it doesn't matter because all of these types require relationship in views in order to get its fields.

I need to generate a JSON output with views that look like this:

{
  'title': 'This is my title',
  'body': '&lt;p&gt;lorem ipsum dolor sit amet.&lt;/p&gt;',
  'blocks': [
    {
      'block_title': 'Block one',
      'block_url': 'www.example.com'
    },
    {
      'block_title': 'Block two',
      'block_url': 'www.site.com'
    },
  ]
}


What I managed to achieve so far, is this:

[
  {
    'title': 'This is my title',
    'body': '&lt;p&gt;lorem ipsum dolor sit amet.&lt;/p&gt;',
    'block_title': 'Block one',
    'block_url': 'www.example.com'
  },
  {
    'title': 'This is my title',
    'body': '&lt;p&gt;lorem ipsum dolor sit amet.&lt;/p&gt;',
    'block_title': 'Block two',
    'block_url': 'www.site.com'
  }
]


This is Drupal 8. Any suggestions?
The data structure you want does not fit with what Views is supposed to provide. Views is intended only for generating lists. 'title' and 'body' are assumed to not be part of a list, so views has no configuration for defining single hardcoded values, and goes against how views works.

Your other option is to create a custom route with a node parameter (example) that returns a JsonResponse object with populated blocks property. So your code may look something like this (based on route parameter example above):


use Drupal\node\NodeInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

class ExampleController {
  function foo(NodeInterface $node) {
    $response = [
      'title' =&gt; $node-&gt;label(),
      'body' =&gt; $node-&gt;get('body')-&gt;first()-&gt;getValue(),
    ];

    $blocks = [];
    $block1 = $node-&gt;get('block')-&gt;get(0)-&gt;get('entity');

    $blocks[] = [
      'block_title' =&gt; $block1-&gt;label(),
      'block_url' =&gt; $block1-&gt;toUrl()-&gt;toString(),
    ];

    /* ... add the rest of the blocks ... */

    $response['blocks'] = $blocks;

    return new JsonResponse($response);
  }
}


The code will need to be adjusted according to your entity field setup.