How to handle json object that was stringified in Python

Question:

I have a question about JSON.stringify() and how to parse it. I have a frontend code and a backend in python (Django).

My fetch function looks like this in frontend.

 const response = await fetch('some-url', {
        method: "POST",
        headers: { 
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
           payload: payload
        })
    });

When i do console.log on JSON.stringify({payload: payload}), its type is string. Then in my backend code, when i print out request.data['payload']), its type is <class ‘dict’>. I am confused why the type changed when i sent the request to the backed. I was going to use json.loads() to parse the payload but since it is already dictionary it returns an error and i can just do request.data['payload'] to access its data.

Can someone explain this behavior?

Asked By: user18431308

||

Answers:

So I guess you are using Django Rest framework.

request.data

Will in Django Rest provide you with a parsed version of the request body. Because you are using the content-type: json it will try and parse it as .. json.

See docs here: https://www.django-rest-framework.org/api-guide/requests/#data

In regular Django for parsing a JSON request it would require the use of json.loads like:

parsed_json = json.loads(request.body)
Answered By: enslaved_programmer