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.

2
  • 1
    And won't. Please look here stackoverflow.com/questions/2904131/… about the difference between json and js object Commented Jun 30, 2015 at 6: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? Commented Jun 30, 2015 at 6:38

1 Answer 1

2

Maybe you should just try this:

json_data = json.dumps(dict(object=response_dict))
Sign up to request clarification or add additional context in comments.

4 Comments

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.
Yes it is. That's what they're doing too.
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.
I'm seeing now. And I also followed aiho's link. Didn't know that much in detail about JSON

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.