Python - how to remove trailing comma (,) in json string

Hi I just started experimenting with python and tornado along with mongodb (I am a beginner). I wrote a simple get function to get all values ​​from my mongodb and return it in JSON format. The problem is that when I try to write the output as a JSON string, I get a trailing comma (,) after the last record from the collection.

class TypeList(APIHandler):
@gen.coroutine
def get(self):
    cursor = db.vtype.find()
    self.write("{"'"success"'": 1, "'"data"'":[")
    while (yield cursor.fetch_next):
        document = cursor.next_object()
        self.write(format(JSONEncoder().encode(document)))
        self.write(",")
    self.write("]}")

class JSONEncoder(json.JSONEncoder):
def default(self, o):
    if isinstance(o,ObjectId):
        return str(o)
    return json.JSONEncoder.default(self, o)

      

And my output is like

{"success": 1, "data":[{"_id": "55a5e988545779f35d3ecdf4", "name": "fgkd", "city": "fghj"},{"_id": 12345.0, "name": "adfs", "city": "asd"},]}

      

Can anyone tell me how I can get rid of this trailing comma (,) after my last entry, because of this comma I am getting an error with an invalid JSON string

I have tried using json dumps

@gen.coroutine
def get(self):
    cursor = db.vtype.find({"brand": "Tata"})
    while (yield cursor.fetch_next):
        document = cursor.next_object()
        self.write(json.dumps(document,default=json_util.default))

      

got the result as

{"Reg": "11ts", "_id": {"$oid": "55a5e988545779f35d3ecdf4"}, "Name": "Alex"}{"Reg": "12ts", "_id": {"$oid": "55a5eac6545779f35d3ecdf5"}, "Name": "asdf"}

Using dumps[{ "data": document }]

I am getting output as

[{"data": {"Name": "asdf", "Reg": "asdfs", "_id": {"$oid": "55a5e988545779f35d3ecdf4"}}}]

[{"data": {"Name": "qwer", "Reg": "asdff", "_id": {"$oid": "55a5eac6545779f35d3ecdf5"}}}]

      

but I want this output to look like this

{"data": [{"Name": "asdf", "Reg": "asdfs", "_id": {"$oid": "55a5e988545779f35d3ecdf4"}},{"Name": "qwer", "Reg": "asdff", "_id": {"$oid": "55a5eac6545779f35d3ecdf5"}}]}

      

If I am doing something wrong, tell me I don’t know how to do it.

+1


source to share


3 answers


There is no reason why you should create JSON documents through text concatenation.



Python has a perfect json

module in the standard library that you should be using. Create your document as a Python dict list, then use json.dumps()

to convert it all to valid JSON.

+6


source


So, is your problem with MongoDB ObjectId

? Then perhaps you should have used bson.json_util

. It may already be installed as part of your MongoDB driver dependencies (which everyone uses pymongo), but if not, then install it.

import bson
import bson.json_util
from bson.json_util import dumps
from bson import ObjectId

dumps({ "a": ObjectId() })

'{"a": {"$oid": "55a782261d41c80b0432b811"}}'

      

Or:



dumps([{ "a": ObjectId(), "b": 1 },{ "a": ObjectId(), "b": 2 }])
'[{"a": {"$oid": "55a79543268e150463d51799"}, "b": 1}, {"a": {"$oid": "55a79543268e150463d5179a"}, "b": 2}]'

      

And it works just like "dumps", except that all BSON type handling is built.

Again, you don't need to reinvent the wheel here and roll your own, because people are already using it.

+2


source


Your JSONEncoder implementation works well. Just use it the way it is intended to be used:

>>> JSONEncoder().encode({'data': [ObjectId(), ObjectId()]})
'{"data": ["<objId>", "<objId>"]}'

      

The coder will take care of serializing dicts, objects, lists, tuples, strings (including unicode), ints, longs, floats, booleans and None. Your implementation also introduces ObjectId

. Fine!

Just lose the string concatenation and use encode

.

0


source







All Articles