CraigH
CraigH

Reputation: 2061

Pymongo & Django query invalid JSON

Im trying to create a JSON result with Pymongo , Mongodb and Django. I have created a Django view that contains a pymongo query and want to return the results in json. However, the results produced arent valid json (according to jsonlint)

Here is my django view.

from django.http import HttpResponse
import pymongo
from datetime import datetime, timedelta
import json
from bson import json_util

#setup database connection
try:
    conn = pymongo.Connection()
    db = conn.mydatabase
except:
    print('Error: Unable to connect to database.')
    conn = None

def querypeople(request):
    result = db.people.find({}).sort('name')
    json_docs = []
    for doc in result:
        json_doc = json.dumps(doc, default=json_util.default, sort_keys=True, indent=4)
        json_docs.append(json_doc)
    return HttpResponse(json_docs, content_type='application/json')

Which produces this output. (Notice commas missing between each document and [ ] should be enclosing the entire result. This makes it invalid JSON.) What am i doing wrong?

"_id": { "$oid": "50c596ab2b9afbbc85ed202a" }, "date_added": { "$date": 1355126443473 }, "name": "Al Landon" }{ "_id": { "$oid": "50c5b9d92b9afbc3f1e7c90c" }, "company": "Corrs", "date_added": { "$date": 1355135449179 }, "name": "Andrew Lumsden", "title": "A Partner"

Upvotes: 1

Views: 502

Answers (1)

sneawo
sneawo

Reputation: 3631

As I understood, you return with response list, not json string. Try:

json_docs = json.dumps(list(result), default=json_util.default, sort_keys=True, indent=4)

Upvotes: 0

Related Questions