简体   繁体   English

Django json序列化不返回对象

[英]Django json serialize doesn't return Object

I'm trying to write an API view for my Django REST API that takes a Location object and serializers it "by hand" -- with json.dumps. 我正在尝试为我的Django REST API编写一个API视图,该视图采用Location对象并“手动”将其序列化-使用json.dumps。 Here's an example: 这是一个例子:

class LocationDetail(APIView):
    def get(self, request, location_id, format=None):
        l = Location.objects.get(id=location_id)
        response_dict = {
            "id": l.id,
            "name" : l.name,
        }
        json_data = json.dumps(response_dict)
        return Response(json_data)

this will, quite unsurprisingly, return a json object, such as this: 毫不奇怪,这将返回一个json对象,例如:

{"name": "Some Place", "id" : 1, ...}

This does not return a proper API response, according to https://www.hurl.it/ . 根据https://www.hurl.it/ ,这不会返回正确的API响应。

But I need the API to return an Object. 但是我需要API返回一个对象。 Here's the version where I use the built-in REST Framework's Serializer class: 这是我使用内置REST框架的Serializer类的版本:

serialized_location = LocationSerializer(l)
return Response(serialized_location.data)

This throws back the "proper" response, and does not cause an error in hurl.it: 这会抛出“正确”的响应,并且不会在hurl.it中导致错误:

Object {id: 1, name: "Some Place", …}

I'd like to figure out how to emulate the behavior of the REST serializer -- how do I get it to return an Object of json instead of just the json? 我想弄清楚如何模拟REST序列化器的行为-如何获取它以返回JSON对象而不是仅返回json?

Here is the difference in images, one is clearly correct and the other just doesn't look like an API response: 这是图片上的差异,一个明显是正确的,而另一个看上去不像API响应:

REST framework serializer: REST框架序列化器:

在此处输入图片说明

My custom json thing: 我的自定义json内容:

在此处输入图片说明

My custom json with "object" key addition: 我的自定义json加上“对象”键:

在此处输入图片说明

They're weirdly different -- I want mine to be recognized as an API response too. 它们之间的差异很奇怪-我也希望我的人也能将其识别为API响应。

SOLUTION: If anyone else is interested, what you can do is just not json dump the object. 解决方案:如果其他人有兴趣,您所能做的就是不对对象进行json转储。 Just return: 只需返回:

return Response(response_dict)

that simple. 这么简单。 That will return an object appropriate for parsing. 那将返回一个适合解析的对象。

也许您应该尝试以下操作:

json_data = json.dumps(dict(object=response_dict))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM