使用PyMongo序列化MongoDB find()返回非匿名JSON数组 [英] Serializing MongoDB find() return into non-anonymous JSON array, using PyMongo

查看:519
本文介绍了使用PyMongo序列化MongoDB find()返回非匿名JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Python代码查询MongoDB,并获取以下对象的一个数组:

My Python code queries a MongoDB and gets back an array of the following objects:

{
    u'attribute': u'value',
    u'_id': ObjectId('534776c66e5987041f6154bd')
}

我想要实现的是返回以下JSON:

What I want to achieve, is to return the following JSON:

{
    'mycollectionkey' : [
        {
            'attribute':'value',
            '_id': ObjectId('534776c66e5987041f6154bd')
        },
        ...and so on.
     ]
}

但是,当我这样做时:

docs = mongodb.find(...query...)
docs_json = bson.json_util.dumps(docs)
return flask.jsonify(success=True,mycollectionkey=docs_json)

我得到:{ 'mycollectionkey' : "*giant string representation of data*" }其中所说的巨型字符串,显然不再是JSON.

I get: { 'mycollectionkey' : "*giant string representation of data*" } where said giant string, clearly is no longer JSON.

推荐答案

此处的问题是,您已经将响应字符串化为JSON,然后再将其传递到另一个数据结构(现在为字符串)中,以便将其返回为JSON.因此,您基本上在进行双重编码,并且字符串"得到了编码.

The problem here is that you already stringified the response as JSON before passing that into another data structure (now as a string) in order to return that as JSON. So you are basically doing a double encode and the "string" gets encoded.

因此只需传递一次数据:

So just pass in the data once:

docs = mongodb.find(...query...)
return bson.json_util.dumps({ 'success': True, 'mycollectionKey': docs })

因此,在这样的一个小收藏集上:

So on a small collection like this:

{ "_id" : ObjectId("5343aeb5efbdb94c3647c8df"), "field" : "BBB" }
{ "_id" : ObjectId("5343aebbefbdb94c3647c8e0"), "field" : "aaa" }
{ "_id" : ObjectId("5343aebfefbdb94c3647c8e1"), "field" : "AAA" }

您会得到如下结果:

{   
    "mycollectionKey": [
        {"field": "BBB", "_id": {"$oid": "5343aeb5efbdb94c3647c8df"}}, 
        {"field": "aaa", "_id": {"$oid": "5343aebbefbdb94c3647c8e0"}}, 
        {"field": "AAA", "_id": {"$oid": "5343aebfefbdb94c3647c8e1"}}
    ], 
    "success": true
}

如果您真的担心这两个键的顺序,则可以使用bson转储"转到一个字符串,然后使用标准json解码器进行解码,以便获得将Mongo对象反序列化的本机字典,然后进一步放入您命令的字典中.

If you are really worried about the order of those two keys then you can use the bson "dumps" to go to a string then decode with the standard json decoder in order to get a native dict with the Mongo objects deserialized, then further put into your ordered dict.

但是实际上您的客户不应该关心密钥的顺序,而只希望那些根元素.

But really your client should not care about the order of the keys and just expect those root elements.

这篇关于使用PyMongo序列化MongoDB find()返回非匿名JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆