Python-如何在JSON字符串中删除最终的逗号(,) [英] Python - how to remove the final comma(,) in json string
问题描述
我刚刚开始对python和龙卷风以及mongodb进行实验(我是新手).我编写了一个简单的get函数,以从mongodb中获取所有值并以JSON格式返回.问题是,当我尝试将输出写为JSON字符串时,在集合中的最后一条记录之后出现了逗号(,).
Hi I have just started experimenting with python and tornado along with mongodb(I am a newbie). I have written a simple get function to get all the values from my mongodb and return it in JSON format. The problem is 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)
我的输出就像
{"success": 1, "data":[{"_id": "55a5e988545779f35d3ecdf4", "name": "fgkd", "city": "fghj"},{"_id": 12345.0, "name": "adfs", "city": "asd"},]}
任何人都可以告诉我如何删除最后一条记录后的尾部逗号(,),因为该逗号,我收到了格式错误的JSON字符串
Can anyone tell me how can I get rid of that trailing comma(,) after my last record, because of that comma I am getting an error malformed JSON string
我已经尝试过使用json转储
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))
将输出作为
{"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"}}]}
如果我做错了什么,请告诉我,我不知道该怎么做.
If I am doing something wrong please tell me I dont know how to do it.
推荐答案
没有理由应该通过文本串联来构建JSON文档.
There is no reason you should be building up JSON documents via text concatenation.
Python在您应该使用的标准库中有一个非常好的json
模块.将文档构建为dicts的Python列表,然后使用json.dumps()
将整个内容转换为有效的JSON.
Python has a perfectly good json
module in the standard library which you should be using. Build up your document as a Python list of dicts, then use json.dumps()
to convert the whole thing to valid JSON.
这篇关于Python-如何在JSON字符串中删除最终的逗号(,)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!