1

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

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

This does not return a proper API response, according to https://www.hurl.it/.

But I need the API to return an Object. Here's the version where I use the built-in REST Framework's Serializer class:

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

This throws back the "proper" response, and does not cause an error in 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?

Here is the difference in images, one is clearly correct and the other just doesn't look like an API response:

REST framework serializer:

enter image description here

My custom json thing:

enter image description here

My custom json with "object" key addition:

enter image description here

They're weirdly different -- I want mine to be recognized as an API response too.

SOLUTION: If anyone else is interested, what you can do is just not json dump the object. Just return:

return Response(response_dict)

that simple. That will return an object appropriate for parsing.

Nick
  • 1,864
  • 5
  • 27
  • 49
  • 1
    And won't. Please look here http://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation about the difference between json and js object – igolkotek Jun 30 '15 at 06:34
  • So if I'm reading correctly, what I have is a JSON string, and what the REST API returns is Object Literal Notation? Or do I have that backwards? – Nick Jun 30 '15 at 06:38

1 Answers1

2

Maybe you should just try this:

json_data = json.dumps(dict(object=response_dict))
bad_keypoints
  • 1,382
  • 2
  • 23
  • 45
  • That just adds the key "object" to it -- still doesn't look like a typical REST API response. I'm going to add some images in the post to clarify. – Nick Jun 30 '15 at 06:21
  • Yes it is. That's what they're doing too. – bad_keypoints Jun 30 '15 at 06:26
  • Okay but did you see the difference in the images? Why is one recognized as some good response and the other just an average key value dictionary? Let me add the image with your object addition too. – Nick Jun 30 '15 at 06:31
  • I'm seeing now. And I also followed aiho's link. Didn't know that much in detail about JSON – bad_keypoints Jun 30 '15 at 07:44