How to return a json object in Google Endpoints

纵饮孤独 提交于 2019-12-08 13:02:46

问题


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

what I use now:

class Response(messages.Message):
  resp = messages.StringField(1)

on the client side I will get something like this

{resp: "{"message": "sucess", "some_data":"data"}"}

and I parse the resp string. However, my desired response will be

{message: "sucess", some_data:"data"}

EDIT: 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


回答1:


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 )

If you only have a json string, you will need to convert to a dictionary first:

jsonDict = json.loads(jsonString)


来源:https://stackoverflow.com/questions/33334600/how-to-return-a-json-object-in-google-endpoints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!