0

In my project, the frontend is in Angular2, I'm making a POST request to a Django url like this:

let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let body = JSON.stringify(this.myMetadata);
let req = this.http.post(this.url,body,options)
  .map((res:Response) => res.json())
  .subscribe(
    data => { this.response = data},
    err => console.error(err),
    () => console.log('done')
  );
  return req;

But the Django backend is not receving the data as JSON

if request.method == 'POST':
    logger.info(request.method)
    logger.info(type(request.body))
    logger.info(request.POST)

log dumps show that Django has received the data as string, due to this none of the json methods work on it.

Method:POST
request.body type:<type 'str'>

What is the best way to resolve this?

is there a way to convert a string to a dictionary?

Bijith komalan
  • 153
  • 1
  • 1
  • 6
  • try to use django rest framework, write serializer and it will convert your json to an object – sebb Sep 14 '16 at 14:57
  • Possible duplicate of [Where's my JSON data in my incoming Django request?](http://stackoverflow.com/questions/1208067/wheres-my-json-data-in-my-incoming-django-request) – C.B. Sep 14 '16 at 14:58

1 Answers1

0

Is there a way to convert a string to a dictionary?

Yes just use the json module

import json
...
if request.method == 'POST':
    data = json.loads(request.body)
    logger.info(type(data))
C.B.
  • 8,096
  • 5
  • 20
  • 34