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
3
  • 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()) Commented Jun 1, 2016 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 Commented Jun 1, 2016 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 Commented Jun 1, 2016 at 13:23

2 Answers 2

4

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

json_object = json.loads(request.body)
Sign up to request clarification or add additional context in comments.

3 Comments

Daniel, I mark your answer as solution because your option translated json into python list which turned out easiest way to loop (d = json.loads(request.body) for x in d: print x['merchandise_id']). @Eduard, your suggested way also worked.
Daniel, can you see this question, please ?
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"]

2 Comments

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
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"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.