【问题标题】:GraphQL query for a single JSON object in GatsbyGatsby 中单个 JSON 对象的 GraphQL 查询
【发布时间】:2019-07-29 11:48:15
【问题描述】:

我有使用 gatsby cli 创建的基本 Gatsby 应用程序,我正在尝试使用来自 @987654323 的 gatsby-transformer-jsongatsby-source-filesystem 插件检索静态 JSON 数据@组件。

我的最终目标是呈现由无头 CMS 生成的静态 JSON 数据。更新 JSON 应该会更新插件生成的 GraphQL 架构。

按照文档并使用this topic 中提供的提示,我设置了以下结构。

测试目的数据如下所示

{
  "name": "first",
  "age": 34,
  "test": "test1",
  "children": [
    {
      "id":1,
      "child":"child1"
    },
    {
      "id":2,
      "child":"child2"
    }
  ]
}

位置如下

 src/data/test/test.json

我的 GraphiQL 查询看起来像这样

{
  testJson {
    name
    age
    children {
      id
      child
    }
  }
}

此查询当前结果如下

 {
      "data": {
        "testJson": {
          "name": "first",
          "age": 34,
          "test": "test1",
          "children": []
        }
      }
    }

由于某种原因,我无法继续查询 children 嵌套数组中的数据。

"children": []

从 CMS 导出的数据包含很多嵌套数组,我目前无法访问。我得到的只是顶层空数组。

我是否在这里遗漏了一个基本概念,或者插件是否在努力从给定的 JSON 解析正确的 GraphQL 架构?

我已彻底阅读文档,但似乎找不到解决方案。

【问题讨论】:

    标签: json graphql gatsby


    【解决方案1】:

    children 用于internallyNodes 之间创建层次结构。

    只需将 children 重命名为其他名称即可:

    {
        "name": "first",
        "age": 34,
        "test": "test1",
        "foos": [
          {
            "id": 1,
            "child": "child1"
          },
          {
            "id": 2,
            "child": "child2"
          }
        ]
    }
    

    现在运行相应的查询:

    {
      testJson {
        name,
        foos {
          id,
          child
        }
      }
    }
    

    结果会如预期:

    {
      "data": {
        "testJson": {
          "name": "first",
          "foos": [
            {
              "id": 1,
              "child": "child1"
            },
            {
              "id": 2,
              "child": "child2"
            }
          ]
        }
      }
    }
    

    【讨论】:

    • 谢谢@mehamasum!有用! PS:没想到像样的命名会给我带来这么多问题。 :)
    猜你喜欢
    • 2021-07-16
    • 2018-10-26
    • 2019-05-18
    • 2020-03-23
    • 2020-08-17
    • 2018-06-16
    • 2019-11-22
    • 2019-04-02
    • 2021-05-29
    相关资源
    最近更新 更多