Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to handle json object that was stringified in Python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can someone explain this behavior?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading