Generate index.json based on sections and subsections

Based on your suggestion I remember the answer of the post “How to build one collection for all nested sections?” which I modified to:

layouts/_default/index.json

{{- $.Scratch.Add "index" slice -}}
{{- range .Site.Sections -}}
    {{- $.Scratch.Add "index" (dict "title" .Title "tags" .Params.tags "categories" .Params.categories "contents" .Plain "permalink" .Permalink) -}}
    {{ template "subpages" . }}
{{- end -}}
{{- $.Scratch.Get "index" | jsonify -}}

{{ define "subpages" }}
  {{ if .Pages }}
    {{ range .Pages}}
      {{ if eq .Kind "section" }}{{- .Scratch.Add "index" (dict "title" .Title "tags" .Params.tags "categories" .Params.categories "contents" .Plain "permalink" .Permalink) -}}{{ end }}
      {{ template "subpages" . }}
    {{ end }}
  {{ end }}
{{ end }}

Now the index.json is not empty anymore BUT only the first level sections are included in the index file. I think the problem is the .Scatch.Add part inside the range. I have to improve the scoping somehow.