Files
JSON
How to define, write and query JSON data.
Define Collection
content.config.ts
import { defineCollection, defineContentConfig, z } from '@nuxt/content'
export default defineContentConfig({
collections: {
authors: defineCollection({
type: 'data',
source: 'authors/**.json',
schema: z.object({
name: z.string(),
avatar: z.string(),
url: z.string()
})
})
}
})
.json
files Create
Create authors files in content/authors/
directory.
{
"name": "Ahad Birang",
"avatar": "https://avatars.githubusercontent.com/u/2047945?v=4",
"url": "https://github.com/farnabaz"
}
{
"name": "Baptiste Leproux",
"avatar": "https://avatars.githubusercontent.com/u/7290030?v=4",
"url": "https://github.com/larbish"
}
Each file in
data
collection should contain only one object, therefore having top level array in a JSON file will cause invalid result in query time.Query Data
Now we can query authors:
<script lang="ts" setup>
// Find a single author
const { data: author } = await useAsyncData('larbish', () => {
return queryCollection('authors')
.where('stem', '=', 'larbish')
.first()
})
// Get all authors
const { data: authors } = await useAsyncData('authors', () => {
return queryCollection('authors')
.order('name', 'DESC')
.all()
})
</script>