我正在尝试将包含产品类别的JSON文件带有 gatsby-transformer-json ,该包含多个具有具有动态子字段的字段的产品它们都在。有数百种不同的类别,因此我想保持这些子字段,例如"属性"动态。他们也可能会随着时间的流逝而改变。客户端逻辑将处理此。
不幸的是,GraphQl只能让我明确地查询字段,并且查询需要知道所有子字段。
这是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"
}
}
]
}
这是一个查询:
query MyQuery {
dataJson {
name
categorydesc
products {
name
attributes {
// This should be dynamic
}
}
}
}
我能想到的一个解决方案是修改attributes
,以使其变为数组:
// 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 },
]
}
然后您可以查询它:
query {
dataJson {
products {
name
attributes {
label
value
}
}
}
}
不幸的是,gatsby-transformer-json
并不那么灵活,我认为如果您想沿着这条路线走,最好编写自己的源插件(听起来不那么困难(,在将数据馈送到Gatsby的范围之前,会转换attributes
字段createNode
。
文档中的一些相关链接:
- https://www.gatsbyjs.org/docs/creating-a-source-plugin/
- https://www.gatsbyjs.org/docs/node-apis/