2

I am using the asyncData method to retrieve the content of a json5 file and I get an empty array.

My file is located at content/myfile.json5

The content is :

[
   {
     id: 1
   },
   {
     id: 21
   }
]

And my method is :

async asyncData({ $content}) {
    const test = await $content('myfile').fetch()

    return {
      test
    }
  }

I am also not able to fetch an array if I use a regular .json file nested in a directory, like /content/places/places.json. The result is an object filled with the first item of my array. It looks like it only works when it's located at the root content folder. I can't find any explanation in the docs.

jbuiquan
  • 21
  • 5

1 Answers1

0

Here is a simple /pages/index.vue file with 2 use cases

<template>
  <pre>{{ nuxtContent }}</pre>
</template>

<script>
export default {
  async asyncData({ $content }) {
    return {
      1️⃣
      // nuxtContent: await $content('testfoobar', { deep: true })
      //   .where({ slug: { $contains: 'yolo' } })
      //   .fetch(),

      2️⃣
      nuxtContent: await $content('testfoobar', 'nice').fetch(),
    }
  },
}
</script>

My project structure enter image description here

nice.json

{
  "name": "bob",
  "age": 25,
  "city": "New York"
}

places.json5

[
  {
    id: 1
  },
  {
    id: 21
  }
]

yolo.json5

[
  {
    id: 777
  },
  {
    id: 999
  }
]

The case 2️⃣ is not working with a .json5 file, not sure if it needs any kind of special syntax or a module to work with it.
Meanwhile, the case 1️⃣ works totally fine with any kind of file (nice.json, places.json5, yolo.json5). And you can also remove the line with the .where to have all of them too.

Here is a screenshot showing 5 objects that I do have in my example (across all the 3 files).

enter image description here

As explained in the documentation here.

PS: if you want to also have hello.md (in the /content directory too), you can use the root path like this: await $content('/', { deep: true }) and you'll get the hello.md + the 5 other nested files.

kissu
  • 40,416
  • 14
  • 65
  • 133
  • Thanks for the answer, I edited my code as it was not reflecting what I wanted to do. The json5 file contains an array and it's that array that I thought getting back from fetch(). To explain a bit more, I want to get a list of items from one json file. In your example, you pass a folder and use deep options to get an array of the directory files! But maybe I misunderstood the correct way of handling content in a workflow like this (one item per file?). – jbuiquan Apr 09 '22 at 18:11
  • @jbuiquan not sure what you do want exactly but I've listed my finding and various approches to get an array of all the objects across all files or per file (with `.where`). Hope it helps! – kissu Apr 10 '22 at 19:15