如何在Google Endpoints中返回json对象
我现在正在做的方式是我有一个带有字符串消息的响应类并返回一个json字符串。在客户端,我解析字符串以将其用作对象。我想知道我们是否可以简单地返回一个json对象,而不是通过解析部分。
The way I'm doing right now is I have a response class with a string message and return a json string. On the client side, I parse the string to use it as a object. I was wondering if we can simply return a json object rather going through the parsing part
现在我使用的是:
class Response(messages.Message):
resp = messages.StringField(1)
在客户端我会得到像这样的东西
on the client side I will get something like this
{resp: "{"message": "sucess", "some_data":"data"}"}
resp
字符串。然而,我想要的回应是
and I parse the resp
string. However, my desired response will be
{message: "sucess", some_data:"data"}
编辑:我意识到我们在消息类下声明每个键的选项,但是我的问题更多地是返回任何泛型json object
Im aware of the option where we state each key under the message class, But my question is more towards returning any generic json object
您可以直接在响应类中定义'message'和'some_data'。例如:
You can define 'message' and 'some_data' on the response class directly. eg:
class Response(messages.Message):
message = messages.StringField(1)
some_data = messages.StringField(2)
jsonDict = {"message": "success", "some_data": "data"}
return Response(**jsonDict )
如果您只有json字符串,则需要先转换为字典:
If you only have a json string, you will need to convert to a dictionary first:
jsonDict = json.loads(jsonString)