JSON looking string (or "\" in output) of Flask Restful/Pymongo JSON output

json validator
json formatter
json example
json syntax
json decode
json viewer
json array
load json file into javascript

First, reference links to other questions I read through. They might be clues to what I am experiencing, although I am not understanding enough yet to see the solution to my problem.

How can I use Python to transform MongoDB's bsondump into JSON?

Unable to deserialize PyMongo ObjectId from JSON

I've got a Flask Restful API I'm working on. An excerpt of my code is as follows:

class DeviceAPI(Resource):

    def get(self, deviceID):
        # do the query
        deviceCollection = db['device']
        device = deviceCollection.find_one({'deviceID': deviceID})

        print device   #1
        print ''

        print json_util.dumps(device)   #2
        print ''

        s = json_util.dumps(device)
        print s  #3
        print ''

        results = {}
        results['device'] = s 

        print results  #4

        # respond
        return results #5

At Print #1, I get the following, and I understand and expect this.

{u'deviceID': u'ABC123', u'_id': ObjectId('....')}

At Print #2 and #3 are identical outputs as expected, and again I understand and expect this (I think).

{"deviceID": "ABC123", "_id": {"$oid": "...."}}

Print #4 has an added key in the dictionary. However, it looks like the value of the key:value is a string where it should be the dictionary as in #2 and #3.

{'device': '{"deviceID": "ABC123", "_id": {"$oid": "...."}}'}

The returned result, #5, according to CURL is along the lines of the following. There are the added / in the there. I suspect because of #4 value looking like a string and that continues in #5 as well.

{"device": "{\"deviceID\": \"ABC123\", \"_id\": {\"$oid\": \"....\"}}"}

I'm trying to get a pure JSON output, not a string representation of the device document. #2 and #3 looked like JSON, but in #4 became a string. Why? And how to do this correctly?


I believe it's because json_utils.dumps is converting your device variable into a string when you should be just returning a complete json object. You essentially end up returning something that resembles this:

return {"device": "a string that resembles json"}

Instead, modify your code to look like this:

class DeviceAPI(Resource):
    def get(self, deviceID):
        # do the query
        deviceCollection = db['device']
        device = deviceCollection.find_one({'deviceID': deviceID})

        results = {'device': device}
        return results

Now, we're returning json that looks more like this:

return {"device": {"deviceID": "ABC123", "_id": {"$oid": "...."}}}

However, it looks like the recommended way to return json in flask is to actually use the flask.jsonify method so that Flask will return a proper response object:

from flask import jsonify

class DeviceAPI(Resource):
    def get(self, deviceID):
        # do the query
        deviceCollection = db['device']
        device = deviceCollection.find_one({'deviceID': deviceID})

        return jsonify(device=device)

JSON Syntax, a string; a number; an object (JSON object); an array; a boolean; null. In JavaScript values can be all of the above,� JSON Uses JavaScript Syntax. Because JSON syntax is derived from JavaScript object notation, very little extra software is needed to work with JSON within JavaScript. With JavaScript you can create an object and assign data to it, like this:


Michael0x2a helped to clear some fog in my mind, and after more experimenting and thinking this through, the following is working for me.

results['device'] = json.loads(json_util.dumps(device))

In my experimenting I was using json_util.dumps and json_util.loads. But I didn't recognize that while json_util.dumps was converting the BSON like item to JSON string, that json_util.loads was converting it directly back. Therefore, another function was needed to take the string like JSON output of json_util.dumps and make it into a dictionary JSON like object. Thus a combo was needed. This is using "import json" and "from bson import json_util" (of Pymongo).

Working with JSON, Use JSON.parse function isJson(str) { try { JSON.parse(str); } catch (e) { return false; } return true; }. How to Get JSON From the Web Server? Getting JSON data from the web server is very easy, you have to make the AJAX request. If the data is received in JSON format, then you can easily parse the string into a JS object. Use XMLHttpRequest to fetch the data from remote server.


Thank you for your reply I had the same problem as you, and it was fixed just because you post back the solution, thanks million! Follow below my code

from flask_restplus import Namespace, Resource, fields
from .. import mongo

import json
from bson import json_util

api = Namespace('inventory', description='Store management related operations')

@api.route('/items')
class Inventory(Resource):
    def get(self):
        inventory_collection = mongo.db.inventory
        resp = inventory_collection.find({})
        a = json.loads(json_util.dumps(resp))
        return {'result': a }


How to test if a string is JSON or not?, JSON (JavaScript Object Notation) is a lightweight data-interchange format. A string is a sequence of zero or more Unicode characters, wrapped in double� A JSON string contains either an array of values, or an object (an associative array of name/value pairs). An array is surrounded by square brackets, [ and ], and contains a comma-separated list of values. An object is surrounded by curly brackets, { and }, and contains a comma-separated list of name/value pairs.


JSON, parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead. Passing in a malformed JSON string results in a JavaScript� A JSON value MUST be an object, array, number, or string, or one of the following three literal names: false null true So, the answer to the question is still yes, JSON text can start with a square bracket (i.e. an array). But in addition to objects and arrays, it can now also be a number, string or the values false, null or true.


JSON, JSON::Parse offers the function "parse_json", which takes a string containing JSON, and returns an The scalar $ebi does not look like Unicode to Perl. no utf8;. A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested. A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java


jQuery.parseJSON(), The JSON.stringify() function, as name suggests, converts a JavaScript value to a serialized JSON string. It optionally uses a replacer function� serializing into JSON will convert it into a string: '{"foo":[1,4,7,10],"bar":"baz"}' which can be stored or sent through wire to anywhere. The receiver can then deserialize this string to get back the original object. {foo: [1, 4, 7, 10], bar: "baz"}.