0

Hello i am trying to develop a simple REST API endpoint using Django rest framework.I tried checking similar questions but did not work.I want my output as (JSON Format):

{
    {
        "id": 1,
        "status": "ONLINE"
    },
    {
        "id": 2,
        "status": "OFFLINE"
    }
}

but my output is (List Format):

[
    {
        "id": 1,
        "status": "ONLINE"
    },
    {
        "id": 2,
        "status": "OFFLINE"
    }
]

My models.py:

class Device(models.Model):
    status = models.CharField(max_length=10, default="OFFLINE")

my serializer.py:

class DeviceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Device
        fields = '__all__'

and my views.py:

def device_list(request):
    devices = Device.objects.all()
    serializer = DeviceSerializer(devices, many=True)
    return Response(serializer.data)
3
  • No idea what you're asking, expected and actual are identical Commented Sep 15, 2020 at 16:37
  • What i want is JSON format what i get is List format Commented Sep 15, 2020 at 16:40
  • 1
    You're misinterpreting your output. the first one isn't valid JSON and couldn't be read by a browser or produced by DRF. Commented Sep 15, 2020 at 16:41

3 Answers 3

4

The output you want is not valid json. {} is for dicts, maps, etc... and [] is for lists.

Sign up to request clarification or add additional context in comments.

Comments

1
def device_list(request):
    devices = Device.objects.all()
    serializer = DeviceSerializer(devices, many=True)
    return Response({"data":serializer.data})

Comments

1
return Response(serializer.data[0])

Comments

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.