3

I have a JSON data that I sent to my server using AJAX. The data comes here and I see it.

def add_collection(self):
        form = AccountForm.LoginForm(request.form)
        if self.request.method == 'GET' :
            return render_template('add_collection.html',user=current_user,formLogin = form)
        elif self.request.method == 'POST' :
            for data in self.request.data :
                print "The data is %s" %data

When I print self.request.data I get my JSON like

    [{"image":"https://mybucket.s3.amazonaws.com/asma.jpg","Description":"Photo Descriptiong"},
{"image":"https://mybucket.s3.amazonaws.com/NCg3G.png","Description":"Photo Description"}]'

The above is exactly what my JSONfile looks like and what I am expecting. However, I want to break it into the two rows and insert into the database. Please how do i loop through JSON. I have seen similar questions here and many more. However, none works for me. When i tried

 for data in self.request.data :
                print data['image']

TypeError: string indices must be integers, not str

Please how do i achieve this ?Any help would be appreciated.

Below is my ajax request .

$.ajax({
                url: "/user/add_collection",
                type: 'POST',
                contentType:'application/json',
                data: JSON.stringify(arr),
                dataType:'json',
                success : function(data,status){
                    console.log("The image upload data returns", data);
                    console.log("the image upload status is", status);
                },
                error : function(xhr, ajaxOptions, thrownError){
                    //$.mobile.loading('hide');
                    if (xhr.status == 200) {
                        alert(ajaxOptions);
                    }
                    else {
                        alert(xhr.status);
                        alert(thrownError);
                    }
                }
            });

I am using python running flask framework .

Community
  • 1
  • 1
Nuru Salihu
  • 4,756
  • 17
  • 65
  • 116

2 Answers2

3

I think you are getting the response as a string (self.request.data). To treat it as objects, you need to convert it (from string to python representation) first:

    elif self.request.method == 'POST' :
        parsed_json = json.loads(self.request.data)
        for data in parsed_json:
            print data['image']
Mirec Miskuf
  • 1,695
  • 1
  • 14
  • 13
2

JSON data is received as a string. You need to parse it first.

data = json.loads(self.request.data)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895