3

I am trying to parse json object in my Django view which has been passed through from client by ajax via post method.

JS:

$.post ('/update_vendor_merchandise_types/', JSON.stringify(json_obj));

View:

def update_vendor_merchandise_types(request):
    print json_object
    # The output gives me  
    # QueryDict: <QueryDict: {u'[{"merchandise_id":"3"},{"merchandise_id":"4"}]': [u'']}>
    json_object = json.load(request.POST) # Error arises
pass

On the commented line 'QueryDict' object has no attribute 'read' error arises. What am I doing wrong ?

Eventually, my goal is to get access to merchandise_id values. I try

d = request.POST.iteritems()
for key, value in d:
    print value

and expect something like

3 
4
Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121
  • 1
    You would do `json.load` to convert json format to a dict. Here, you have a dict you want to convert to `json`. You would be doing `json.dumps(request.POST.copy())` – karthikr Jun 01 '16 at 13:15
  • 2
    What are you actually trying to do? `request.POST` is a dictionary which should contain any data you actually need, there isn't any point jsonifying it – Sayse Jun 01 '16 at 13:20
  • I have edited the question. Please see the value of the json_object. I am trying to loop over it. Say, print all the merchandise_id and respective value values – Edgar Navasardyan Jun 01 '16 at 13:23

2 Answers2

4

request.POST is for form-encoded content. For JSON, you should access the plain body directly:

json_object = json.loads(request.body)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
4

Why do you convert json_obj into string when sending it to server? I think you should do it in this way:

json_obj = {"key1": "value1", "key2": "value2"}
$.post('/update_vendor_merchandise_types/', json_obj)  

In this case on the server side you can access sent data in this way:

v1 = request.POST["key1"]
Eduard Stepanov
  • 1,183
  • 8
  • 9
  • Eduard, actually, I would like the code of the loop to be as generic as possible, and I want to avoid addressing the json elements by their field names. Instead, my ultimate goal is to loop over it – Edgar Navasardyan Jun 01 '16 at 13:44
  • 1
    may be your json_obj should look like this: `{"merchandise_ids": ["3", "4"]}`, in this case you can get on a server a list of merchandise ids by executing `ids = request.POST["merchandise_ids"]` – Eduard Stepanov Jun 01 '16 at 13:57