嗨,我刚刚开始尝试 python、tornado 和 mongodb(我是新手)。我编写了一个简单的 get 函数来从 mongodb 获取所有值并以 JSON 格式返回。问题是,当我尝试将输出写入 JSON 字符串时,我在集合中的最后一条记录后面得到一个尾随逗号 (,)。
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)
我的输出就像
{"success": 1, "data":[{"_id": "55a5e988545779f35d3ecdf4", "name": "fgkd", "city": "fghj"},{"_id": 12345.0, "name": "adfs", "city": "asd"},]}
谁能告诉我如何去掉最后一条记录后的尾随逗号(,),因为该逗号我收到错误格式错误的 JSON 字符串
我尝试过使用 json 转储
@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))
得到输出为
{"Reg": "11ts", "_id": {"$oid": "55a5e988545779f35d3ecdf4"}, "Name": "Alex"}{"Reg": "12ts", "_id": {"$oid": "55a5eac6545779f35d3ecdf5"}, "Name": "asdf"}
使用时dumps[{ "data": document }]
我得到的输出为
[{"data": {"Name": "asdf", "Reg": "asdfs", "_id": {"$oid": "55a5e988545779f35d3ecdf4"}}}]
[{"data": {"Name": "qwer", "Reg": "asdff", "_id": {"$oid": "55a5eac6545779f35d3ecdf5"}}}]
但我想要这样的输出
{"data": [{"Name": "asdf", "Reg": "asdfs", "_id": {"$oid": "55a5e988545779f35d3ecdf4"}},{"Name": "qwer", "Reg": "asdff", "_id": {"$oid": "55a5eac6545779f35d3ecdf5"}}]}
如果我做错了什么,请告诉我,我不知道该怎么做。