Files
JSON
How to define, write and query JSON data.
Define Collection
content.config.ts
export const 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:
// Find a single author
const theAuthor = await queryCollection('authors')
.where('stem', '=', 'larbish')
.first()
// Get all authors
const authors = await queryCollection('authors')
.order('name', 'DESC')
.all()