作者:那是黑夜过后的黎明_182 | 来源:互联网 | 2022-12-07 18:24
我在python(Flask + Graphene)中有一个后端服务器,我需要返回一个这样的JSON对象:
{
's1': "Section 1",
's2': "Section 2",
's3': "Section 3",
's4': "Section 4"
}
解析器如下所示:
questiOnnaire= graphene.types.json.JSONString(
description='JSON result test')
def resolve_questionnaire(self, info: graphql.ResolveInfo):
sectiOns= {
's1': "Section 1",
's2': "Section 2",
's3': "Section 3",
's4': "Section 4"
}
print(json.dumps(sections))
return sections
在控制台中我看到了print(json.dumps(sections))
我期望的结果:
user-api_1 | {"s1": "Section 1", "s2": "Section 2", "s3": "Section 3", "s4": "Section 4"}
但在GraphiQL中,我看到所有带反斜杠的引号:
当我更改为时return sections
,return json.dumps(sections)
我得到如下结果:
问题是如何在石墨烯解析器中正确返回JSON对象?
我知道有像这里使用的json.replace方法,但我相信我只是以错误的方式生成/传递对象.
1> 小智..:
你的初步结果
{
"data": {
"questionnaire": "{\"s1\": \"Section 1\", \"s2\": \"Section 2\", \"s3\": \"Section 3\", \"s4\": \"Section 4\"}"
}
}
是预期的行为.毕竟,questionnaire
解析为JSON 字符串.由于它是一个字符串,因此必须双引号,因此必须对其内部引用进行转义.这符合JSON的标准.
要使用该字符串,必须在data.questionnaire
对象上运行某种JSON解析器.例如,在Javascript中,它会是这样的:
var data;
// Fetching logic to get the data object from your GraphQL server
var sectiOns= JSON.parse(data.questionaire);
// Now you can access its objects
console.log(sections.s1) // Should print "Section 1" on the dev console
然而,如果密钥sections
不是预定的(sections.s5
可以在一种情况下定义但在另一种情况下未定义),则上述方法并不理想.相反,您可能更愿意拥有一个可以迭代的数组.为此,您必须定义具有显式键值对的"模型".这样做的格式也适用于GraphQL.例如:
import graphene
# Our new model
class Section(graphene.ObjectType):
key = graphene.String() # dictionary key
header = graphene.String() # dictionary value
# Your previous schema with modifications
class Query(graphene.ObjectType):
# questiOnnaire= graphene.types.json.JSONString(description='JSON result test')
# Return a list of section objects
questiOnnaire= graphene.List(Section)
def resolve_questionnaire(self, info: graphql.ResolveInfo):
sectiOns= {
's1': "Section 1",
's2': "Section 2",
's3': "Section 3",
's4': "Section 4"
}
sections_as_obj_list = [] # Used to return a list of Section types
# Create a new Section object for each item and append it to list
for key, value in sections.items(): # Use sections.iteritems() in Python2
section = Section(key, value) # Creates a section object where key=key and header=value
sections_as_obj_list.append(section)
# return sections
return sections_as_obj_list
现在,如果我们运行查询:
query {
questionnaire {
key
header
}
}
它返回一个可以迭代的JSON数组.
{
"data" {
"questionnaire": [
{
"key": "s1",
"header": "Section 1"
},
{
"key": "s2",
"header": "Section 2"
},
{
"key": "s3",
"header": "Section 3"
},
{
"key": "s4",
"header": "Section 4"
},
]
}
}