kvasnicaj
kvasnicaj

Reputation: 602

Added escaped quotes to JSON in Flask app with mongoDB

I am trying to create API for my Flask project. I have data stored in mongoDB and for building API I am using flask_restful. The problem is that in JSON are added escaped quotes and I cannot figure why and I rather have my JSON without them.

This is how my get function looks like:

from flask_restful import Resource
import json
from bson import json_util

class Harvests(Resource):

    def get(self):
        json_docs = []

        for doc in db.collection.find():
            json_doc = json.dumps(doc, default=json_util.default)
            json_docs.append(json_doc)

        return json_docs

In app.py it is just like that

api = Api(app)
api.add_resource(Harvests, '/api/harvests')

And I get JSON with escaped quotes (in browser or with curl)

[
"{\"_id\": {\"$oid\": \"5c05429cc4247917d66163a7\"},...
]

If I try this outside Flask (print JSON from mongo) and it works just fine. I tried use .replace(), but I think is not most elegant solution, but it did not work anyway. Any idea how I should get rid off these backslashes?

Upvotes: 0

Views: 1370

Answers (1)

Alfe
Alfe

Reputation: 59516

What you see is absolutely what you should expect to see according to your code, so I think there is a misunderstanding at some point. Let me explain what you are doing.

You convert each doc (a data structure) into a jsonified version (a string) of this data. Then you gather these strings in a list. Later you see this list, and of course you see a list of strings. Each of these strings contains a jsonified version of a data structure (a dictionary with opening braces, keys and values inside, and each key is a string itself with quotes, so these quotes are escaped within the jsonified string).

I recommend to collect your documents into a list and then convert that list to json instead:

def get(self):
    docs = []

    for doc in db.collection.find():
        docs.append(doc)

    return json.dumps(docs, default=json_util.default)

This way you get one json string representing the list of docs.

Maybe your framework is already applying a jsonifying automatically, in this case just don't do this step yourself:

    return docs

Just use this instead.

Upvotes: 2

Related Questions