I have:
- src
- data
- data.json
data.json:
"gallery": [
{"name":...
{"name":.. ...
gatsby-config.js contains:
`gatsby-transformer-json`,
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/src/data`,
name: `data`,
},
},
How can I get list of gallery.names from this json-file via GraphQL query? I'm trying to write:
export const IndexQuery = graphql`
query IndexQuery {
mydata: file(name: { eq: "data" }, extension: { eq: "json" }) {
allFile {
gallery {
name
}
}
}
}
`
but it doesn't work.
To extract the name and projects properties from the JSON string, use the json_extract function as in the following example. The json_extract function takes the column containing the JSON string, and searches it using a JSONPath -like expression with the dot . notation. JSONPath performs a simple tree traversal.
GraphQL services typically respond using JSON, however the GraphQL spec does not require it. JSON may seem like an odd choice for an API layer promising better network performance, however because it is mostly text, it compresses exceptionally well with GZIP.
Your GraphQL query needs a little tweaking. The gatsby-transformer-json
takes care of all the resolving, so you don't need to worry about gatsby-source-filesystem
inside the query:
export const IndexQuery = graphql`
query IndexQuery {
dataJson {
gallery {
name
}
}
}
`;
Then use it inside the page/layout like:
this.props.data.dataJson.gallery
To debug your GraphQL queries it’s helpful to use the built-in GraphiQL, which should run at http://localhost:8000/___graphql.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With