Pass JSON data to inline Javascript

So I have another noobish question about accessing data and passing it to inline JS
I want to pass all the file names to a javascript array. But I’m not getting the syntax right.

  {{ $sb := $.Site.Data.sketchbook }}
  {{ with $sb }}
  {{ range .resources }}
  {{ $output := slice .filename }}
  {{ end }}
  {{ end }}
  <script type="text/javascript">
  const sketchbook = [ {{ $output }}];
  console.log(sketchbook);
  </script>  

My JSON file is shaped like this:

{
  "resources": [
    {
     "url": "https://example.com/mysketch.png"
     "other": "anotherthing",
     "filename": "mysketch",
     "alt": "the alt text",
    },
    {
     "url": "https://example.com/mydifferentSketch.webp"
     "other": "anotherthing",
     "filename": "mydifferentSketch",
     "alt": "the alt text",
    },    
   ]
  }

How can I properly get the filenames, and insert them into the JS array as strings?

Thanks!

Have you tried importing the JSON file?

import * as data from './example.json';
{{ with site.Data.sketchbook }}
  {{ $filenames := slice }}
  {{ range .resources }}
    {{ $filenames = $filenames | append .filename }}
  {{ end }}
  <script type="text/javascript">
    const sketchbook = {{ $filenames }};
    console.log(sketchbook);
  </script>
{{ end }}
2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.