Home > Software design >  how to make FILE type json serializable
how to make FILE type json serializable

Time:06-02

I am trying to send json response in django but I am getting this error

TypeError: Object of type File is not JSON serializable

Error is coming because I am using type <class 'django.core.files.base.File'> in json response. So how can I convert this to json serializable formate?

Code:

        user_id = User.objects.get(id=token_data['user_id'])
        all_posts = publicPost.objects.filter(user_id=user_id)
        post_ids = [] 
        for post in all_posts:
            post_ids.append(post.id)
        images = {} 
        for id in post_ids:
            img_obj =  PostImage.objects.filter(post_id=id) 
            imgs = [img_obj[0].image.file] 
            try:
                x = img_obj[0].other_image1.file
                imgs.append(x)
            except ValueError:
                pass
            try:
                x = img_obj[0].other_image2.file
                imgs.append(x)
            except ValueError:
                pass
            try:
                x = img_obj[0].other_image2.file
                print('type', type(x))
                imgs.append(x)
            except ValueError:
                pass 

            images[id] = imgs 
            
        return JsonResponse({'posts': post_ids, 'images': images})

CodePudding user response:

Serialize the url, not the image:

img_obj[0].image.url

instead of

img_obj[0].image.file

CodePudding user response:

if you really need to send a file in a response you can try to convert it to bytes first.

images = [bytes(img).decode('utf8') for img in images]
  • Related