gpt4 book ai didi

python - Graphite 烯 graphql 字典作为一种类型

转载 作者:太空狗 更新时间:2023-10-29 22:28:49 27 4
gpt4 key购买 nike

我是 Graphite 烯的新手,我正在尝试将以下结构映射到对象类型,但完全没有成功

    {
"details": {
"12345": {
"txt1": "9",
"txt2": "0"
},
"76788": {
"txt1": "6",
"txt2": "7"
}
}
}

非常感谢任何指导
谢谢

最佳答案

目前尚不清楚您要完成什么,但是(据我所知)在定义 GraphQL 模式时您不应该有任何任意的键/值名称。如果你想定义一个字典,它必须是显式的。这意味着“12345”和“76788”应该有为它们定义的 key 。例如:

class CustomDictionary(graphene.ObjectType):
key = graphene.String()
value = graphene.String()

现在,要完成类似于您所要求的模式,您首先需要定义适当的类:

# Our inner dictionary defined as an object
class InnerItem(graphene.ObjectType):
txt1 = graphene.Int()
txt2 = graphene.Int()

# Our outer dictionary as an object
class Dictionary(graphene.ObjectType):
key = graphene.Int()
value = graphene.Field(InnerItem)

现在我们需要一种方法来将字典解析为这些对象。使用您的字典,这是一个如何做到这一点的例子:

class Query(graphene.ObjectType):

details = graphene.List(Dictionary)
def resolve_details(self, info):
example_dict = {
"12345": {"txt1": "9", "txt2": "0"},
"76788": {"txt1": "6", "txt2": "7"},
}

results = [] # Create a list of Dictionary objects to return

# Now iterate through your dictionary to create objects for each item
for key, value in example_dict.items():
inner_item = InnerItem(value['txt1'], value['txt2'])
dictionary = Dictionary(key, inner_item)
results.append(dictionary)

return results

如果我们查询这个:

query {
details {
key
value {
txt1
txt2
}
}
}

我们得到:

{
"data": {
"details": [
{
"key": 76788,
"value": {
"txt1": 6,
"txt2": 7
}
},
{
"key": 12345,
"value": {
"txt1": 9,
"txt2": 0
}
}
]
}
}

关于python - Graphite 烯 graphql 字典作为一种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46402182/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com