Gatsby中来自单个对象JSON文件的GraphQL模式 [英] GraphQL schema from a single object JSON file in Gatsby

查看:111
本文介绍了Gatsby中来自单个对象JSON文件的GraphQL模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想查询单个JSON文件,该文件不是Gatsby的GraphQL的数组,但我真的不知道该怎么做.

So I'd like to query a single JSON file which is not an array from Gatsby's GraphQL but I don't really know how to do it.

据我了解的gatsby-transformer-json文档-它仅支持加载数组并通过allFileNameJson模式对其进行访问.

As far as I understand gatsby-transformer-json docs - it only supports loading arrays and have them accessible via allFileNameJson schema.

我的gatsby-config插件(仅此问题所需的插件):

My gatsby-config plugins (only the necessary ones for this question):

{
  resolve: 'gatsby-source-filesystem',
  options: {
    name: 'data',
    path: `${__dirname}/src/data`
  }
},
'gatsby-transformer-json'

然后在src/data中说我有一个something.json文件,如下所示:

And then let's say in src/data i have a something.json file, like this:

{
  "key": "value"
}

现在,我想从something.json文件中查询数据,但是没有可以查询的somethingJson模式(与Gatsby的GraphiQL一起尝试过).

Now I'd like to query the data from something.json file, but there is no somethingJson schema i can query (tried with Gatsby's GraphiQL).

有人可以指出我做错了什么或如何解决这个问题?

Could someone point out what am I doing wrong or how can I solve this problem?

推荐答案

好,因此,只要它们具有父级(文件夹),就可以查询单对象文件.

Ok, so it is possible to query single-object files as long as they have a parent (folder).

让我们采用以下参数:

  • gatsby-source-filesystem配置为src/data
  • test.json文件位于src/data/test.json中,其中包含{ "key": "value" }内容
  • gatsby-source-filesystem configured to src/data
  • test.json file positioned at src/data/test.json with { "key": "value" } content in it

现在,由于test.json文件实际上有一个父级(data文件夹)-您可以像这样查询test.json中的字段:

Now as the test.json file actually has a parent (data folder) - you can query the fields from test.json like this:

{
  dataJson {
    key
  }
}

但是将它们直接放在根文件夹中是一个坏习惯,因为当您存储另一个json文件(即具有{ "key2": "value2" }内容的secondtest.json),并使用与上面相同的查询对其进行查询时,您将获得数据仅来自单个节点(不确定是第一个节点还是最后一个遇到的节点),

But putting those directly in your root folder is a bad practice, because when you will store another json file, i.e. secondtest.json with { "key2": "value2" } content, and will query it with the same query as above, you will get data only from a single node (not sure if it takes first, or last encountered node),

因此,这种情况的理想解决方案是将您的单对象json文件存储在单独的文件夹中,每个文件夹仅包含一个json.

So, the perfect solution for this case is to have your single-object json files stored in separate folders with just one json per folder.

例如,您有一些关于我"数据:

For example you have some "About Me" data:

  1. src/data
  2. 中创建一个about文件夹
  3. 使用{ "name": "John" }
  4. 创建index.json文件
  5. 查询您的数据
  1. create a about folder in your src/data
  2. create an index.json file with i.e. { "name": "John" }
  3. query your data

赞:

{
  aboutJson {
    name
  }
}

就是这样.

这篇关于Gatsby中来自单个对象JSON文件的GraphQL模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆