Max Kehayov
Max Kehayov

Reputation: 51

GraphQL query for a single JSON object in Gatsby

I have the basic Gatsby app created with gatsby cli and I am trying to retrieve static JSON data using the gatsby-transformer-json and gatsby-source-filesystem plugins from a StaticQuery component.

My end goal is to render static JSON data, generated by a headless CMS. Updating the JSON should update the GraphQL schema generated by the plugins.

Following the docs and using the tip, provided in this topic, I have set up the following structure.

Testing purpose data looks like this

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

it is located as follows

 src/data/test/test.json

and my GraphiQL query looks like this

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

This query currently results in the following

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

For some reason I am not able to proceed querying data in a the children nested array.

"children": []

The data exported from the CMS consists of a lot of nested arrays, which I currently cannot access. All I get is the top level empty array.

Am I missing a fundamental concept here or are the plugins struggling to parse a proper GraphQL schema from the given JSON?

I have read the documentation thoroughly and cannot seem to find a solution.

Upvotes: 3

Views: 1422

Answers (1)

mehamasum
mehamasum

Reputation: 5742

children is used internally for creating hierarchy between Nodes.

Just rename children to something else and it will be fine:

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

Now run the corresponding query:

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

The result will be as expected:

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

Upvotes: 8

Related Questions