Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

graphql

gatsby

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.

like image 274
angry Avatar asked Mar 13 '18 09:03

angry


People also ask

Can we extract the data from JSON file?

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.

Does GraphQL work with JSON?

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.


1 Answers

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.

like image 142
Fabian Schultz Avatar answered Oct 28 '22 07:10

Fabian Schultz