-2

I want to avail a feature with which data can be fetched from database(sqlite3) and downloaded as a .json file. the data present in database are emails which has fields like to,from etc. I am facing problem in fetching and then writing it to .json. the data i am getting is an object which is giving this error while writing to .json "<UserData: UserData object> is not JSON serializable" . Below I have give few code snippets, please do help..


If data can be fetched in this format then work is done!!:) but I dunno how to implement?:(

[{'body': {'markdown': u'http://127.0.0.1:8000/admin/gextracto/userdata/', 'html': u'http://127.0.0.1:8000/admin/gextracto/userdata/\r<br/>'}, u'To': u'infowikitech@gmail.com', u'From': u'Gextracto <infowikkitech@gmail.com>', 'id': u'151202ad347314bc', u'Subject': u'Your Download Ready!'}]

but it is coming in this format-

[<UserData: UserData object>, <UserData: UserData object>, <UserData: UserData object>, <UserData: UserData object>, <UserData: UserData object>, <UserData: UserData object>, <UserData: UserData object>, <UserData: UserData object>, <UserData: UserData object>, <UserData: UserData object>, <UserData: UserData object>, <UserData: UserData object>, <UserData: UserData object>]

this is where i am retrieving the data-

def get(self,request, format=None):
        label_id = request.GET['label']
        all_mails=UserData.objects.filter(label=label_id)
        return Response(all_mails)

This is where i am writing is to .json-

function bulk_download_json(label_id){

    $.ajax({
        type:"GET",
        url:"/initiate_download/?label="+label_id,
        success:function(data){
            bulk_mails=data;

            bulk_download_filename = label_id.concat(".json");

            var bulk_json_file = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(bulk_mails));
            $('<a id="bulk_json_link" href="data:' + bulk_json_file + '" download="'+bulk_download_filename+'">download JSON</a>').appendTo('#bulk_json_content');
            document.getElementById('bulk_json_link').click();  
        }
    });
}
pkt
  • 53
  • 12

1 Answers1

2

You need to convert the data into a json here.

Run this query first,which will display the data into the known format.

data = your_db.objects.all().values()

After this is done, you may use,

import json
data_json = json.loads(dumps(data))

Also this link may help you more.('django serialize queryset.values() into json')

Community
  • 1
  • 1
Rahul
  • 2,580
  • 1
  • 20
  • 24
  • Thanks I am glad that it works .Please accept the answer then :-) – Rahul Nov 21 '15 at 04:32
  • @RahulLakhanpal, Why would the op accept the poorest answer? – 7stud Nov 21 '15 at 04:39
  • Considering the fact that he hasn't used serializers, my solution provides a quick way out to get things working. However I did post the link which would have helped him more. – Rahul Nov 21 '15 at 04:42