0
votes

I'm trying to import JSON files containing product categories with gatsby-transformer-json that contain multiple products with fields which have dynamic sub fields depending on the category they are in. There are hundreds of different categories so I would like to keep these subfields like "attributes" dynamic. They also might change over time. The client logic would handle this.

Unfortunately GraphQL only let's me query fields explicitly and the query needs to know all subfields.

This is the JSON:

{
    "name": "Car Hifi",
    "categorydesc": "This should be a very long text",
    "products": [{
            "name": "JVC KW-DB93BT",
            "attributes": {
                "Has USB": "JVC",
                "compatible formats": {},
                "Hands free": "true"
            },
            "advantages": {
                "0": "More bass",
                "1": "Less power consumption",
                "2": "Simple UI"
            }
        }
    ]
}

and this a query:

query MyQuery {
  dataJson {
    name
    categorydesc
    products {
      name
      attributes {
        // This should be dynamic
      }
    }
  }
}
1

1 Answers

0
votes

One solution I can think of is to modify the attributes so that it becomes an array instead:

// from this
{
  "attributes": {
    "Has USB": "JVC",
    "compatible formats": {},
    "Hands free": "true"
  }
}

// to this
{
  "attributes": [
    {"label": "Has USB", "value": "JVC" },
    {"label": "compatible formats", "value": {} },
    {"label": "Hands free", "value": true },
  ]
}

Then you can query it:

query {
  dataJson {
    products {
      name
      attributes {
        label
        value
      }
    }
  }
}

Unfortunately gatsby-transformer-json is not that flexible, I think if you want to go down this route it's better to write your own source plugin (which isn't as difficult as it sounds) that transform the attributes field before feeding the data to Gatsby's createNode.

A few relevant links from the docs: