How Can I Get Data From A Json Via Graphql?
Solution 1:
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:
importReactfrom"react"importJSONData from"../../content/My-JSON-Content.json"constSomePage = () => (
<divstyle={{maxWidth: `960px`, margin: `1.45rem` }}><ul>
{JSONData.compdata.map((data, index) => {
return <likey={`content_item_${index}`}>{data.title}</li>
})}
</ul></div>
)
exportdefaultSomePageIn 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.
Post a Comment for "How Can I Get Data From A Json Via Graphql?"