Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

javascript - How can I get data from a json via GraphQL?

enter code here {
 "compdata": [
{
  "id": 1,
  "title": "FlexBox",
},
{
  "id": 2,
  "title": "Grid layout",
},

] }

enter code here **file in:-- src-data-data.json**
enter code here export const IndexQuery = graphql`
query IndexQuery {
dataJson {
compdata {
  id
  example
}

} } `

Blockquote giving me error Cannot read properties of undefined (reading 'compdata')

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You only need to follow the docs about Sourcing from JSON.

That said, you don't need to use GraphQL when sourcing from a JSON local file, you can just import the object such as:

import React from "react"
import JSONData from "../../content/My-JSON-Content.json"

const SomePage = () => (
  <div style={{ maxWidth: `960px`, margin: `1.45rem` }}>
    <ul>
      {JSONData.compdata.map((data, index) => {
        return <li key={`content_item_${index}`}>{data.title}</li>
      })}
    </ul>
  </div>
)
export default SomePage

In this case, you can import your JSON data as JSONData and loop it through the array of compdata.

However, if you still want to use GraphQL, you will need to use the gatsby-transformer-json plugin, what will create a queryable GraphQL node from your JSON source:

Install it by:

npm install gatsby-transformer-json

And use it your gatsby-config.js:

module.exports = {
  plugins: [
    `gatsby-transformer-json`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `./src/your/json/folder`,
      },
    },
  ],
}

The alias of the node will rely on your folder structure and your naming (which hasn't been provided), in the docs example, given a letters.json such as:

[{ "value": "a" }, { "value": "b" }, { "value": "c" }]

So in your GraphiQL playground (localhost:8000/___graphql) you will be able to query allLettersJson node:

 {
  allLettersJson {
    edges {
      node {
        value
      }
    }
  }
}

You can add a typeName option to fix your naming such as:

{
  resolve: `gatsby-transformer-json`,
  options: {
    typeName: `Json`,
  },
},

In that case, the created node will be allJson.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...