1

the request.body contains this:

"event=project.status.update&project_id=807276&project_status_code=in_progress"

but when I do:

json.loads(request.body)

I am getting:

ValueError: No JSON object could be decoded

what am I doing wrong?

ferrangb
  • 2,012
  • 2
  • 20
  • 34
doniyor
  • 36,596
  • 57
  • 175
  • 260
  • 1
    `json.dumps` takes a python dictionary/JSON object and the counter function, `json.loads` takes a json string. You can't do `dumps/loads` on a form encoded string. Whoever is making this http request, they can do JSON.stringify, make a valid json string, set their `Content-type`, header as `application/json` and send it –  Aug 13 '15 at 09:40
  • @MadhavanKumar sorry, wrong function name, I meant loads() – doniyor Aug 13 '15 at 09:41
  • @doniyor But it's still not valid JSON. You need to make it a JSON format to load it as a JSON object. – SuperBiasedMan Aug 13 '15 at 09:42
  • @SuperBiasedMan how to do that? – doniyor Aug 13 '15 at 09:43
  • `'{"event": "project.status.update", "project_id": "807276", "project_status_code": "in_progress"}'` – amarnath Aug 13 '15 at 09:46
  • @doniyor I'm not very familiar with Django, is the format of `request.body` always `"key=value&key=value&key=value"`? – SuperBiasedMan Aug 13 '15 at 09:50
  • 1
    Why are you trying to load this as JSON? It's a standard POST, which you can get as a querydict from `request.POST`. – Daniel Roseman Aug 13 '15 at 10:19
  • @DanielRoseman right, but in the API docs i am working with, they say i need to expect for json data in callback, but the real data isnot json, i didnot know that this data is plain post body – doniyor Aug 13 '15 at 11:48

3 Answers3

3

request.body contains form-encoded data, not json-encoded data. This is automatically decoded to a Python dict in request.POST. So, instead of using request.body directly with json.loads, you should be using request.POST.

knbk
  • 52,111
  • 9
  • 124
  • 122
0

json.dumps takes a python dictionary/JSON object and the counter function, json.loads takes a json string.

You can't do dumps/loads on a form encoded string.

Whoever is making this http request, they can do JSON.stringify, make a valid json string out of form data object, set their Content-type, header as application/json and send it

SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
-1

Your JSON string must be like the below one in order to use json.loads()

'{
    "event": "project.status.update", 
    "project_id": "807276", 
    "project_status_code": "in_progress"
}'
amarnath
  • 785
  • 3
  • 19
  • 23
  • Though this technically answers the question it's not a practical solution that allows the asker to fix the problem. Manually changing this instance of a string into a dictionary isn't a solution that will work next time. – SuperBiasedMan Aug 13 '15 at 10:36