---
title: "JSON"
description: "如何定义、编写和查询 JSON 数据。"
canonical_url: "https://nuxt-content.zhcndoc.com/docs/files/json"
---
# JSON

> 如何定义、编写和查询 JSON 数据。

## 定义集合

```ts [content.config.ts]
import { defineCollection, defineContentConfig } from '@nuxt/content'
import { z } from 'zod'

export default defineContentConfig({
  collections: {
    authors: defineCollection({
      type: 'data',
      source: 'authors/**.json',
      schema: z.object({
        name: z.string(),
        avatar: z.string(),
        url: z.string()
      })
    })
  }
})
```

## 创建 `.json` 文件

在 `content/authors/` 目录下创建作者文件。

<code-group>

```json [farnabaz.json]
{
  "name": "Ahad Birang",
  "avatar": "https://avatars.githubusercontent.com/u/2047945?v=4",
  "url": "https://github.com/farnabaz"
}
```

```json [larbish.json]
{
  "name": "Baptiste Leproux",
  "avatar": "https://avatars.githubusercontent.com/u/7290030?v=4",
  "url": "https://github.com/larbish"
}
```

</code-group>

<warning>

`data` 集合中的每个文件应仅包含一个对象，因此在 JSON 文件中使用顶层数组会导致查询时结果无效。

</warning>

## 查询数据

现在我们可以查询作者：

```vue
<script lang="ts" setup>
// 查找单个作者
const { data: author } = await useAsyncData('larbish', () => {
  return queryCollection('authors')
    .where('stem', '=', 'authors/larbish')
    .first()
})

// 获取所有作者
const { data: authors } = await useAsyncData('authors', () => {
  return queryCollection('authors')
    .order('name', 'DESC')
    .all()
})
</script>
```


## Sitemap

See the full [sitemap](https://nuxt-content.zhcndoc.com/sitemap.md) for all pages.
