Python - 如何删除 json 字符串中的最后一个逗号 (,)

标签 python json

您好,我刚刚开始尝试使用 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”},“名称”:“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"}}]}

如果我做错了什么,请告诉我我不知道该怎么做。

最佳答案

您没有理由通过文本连接构建 JSON 文档。

Python 在标准库中有一个非常好的 json 模块,您应该使用它。将您的文档构建为 Python 字典列表,然后使用 json.dumps() 将整个内容转换为有效的 JSON。

关于Python - 如何删除 json 字符串中的最后一个逗号 (,),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31450221/

相关文章:

PHP 消费 JSON 流

python - 为什么 Pandas 默认遍历 DataFrame 列?

python - 在 SQLAlchemy 中使用连词进行查询

python - Pandas 函数用于从数据帧生成系列

json - NodeJs - 嵌套 JSON POST 输入

javascript - JSON 到 Javascript

php - mysql表中导入的表情符号和json_encode

python - 在 Google App Engine 上模拟浏览器

python - Elastic Beanstalk :/bin/sh:/opt/python/run/venv/bin/activate: No such file or directory

Android - 如何在 Child 中获取 JSON 数组