반응형
MongoDB 쿼리를 JSON으로 변환하려면 어떻게 해야 하나요?
for p in db.collection.find({"test_set":"abc"}):
posts.append(p)
thejson = json.dumps({'results':posts})
return HttpResponse(thejson, mimetype="application/javascript")
내 Django/Python 코드에서 "Object" 때문에 mongo 쿼리에서 JSON을 반환할 수 없습니다.ID. 오류에 "개체"가 표시됩니다.ID"는 일련화할 수 없습니다.
어떻게 해야 하죠?해킹 방법은 다음과 같습니다.
for p in posts:
p['_id'] = ""
오브젝트 등의 이유로 json 모듈이 작동하지 않습니다.아이디
다행히 PyMongo는 json_util을 제공하고 있습니다.
...BSON 문서를 Mongo Extended JSON의 Strict 모드로 특수 인코딩 및 디코딩할 수 있습니다.이를 통해 특수 BSON 유형을 사용하는 경우에도 BSON 문서를 JSON으로 인코딩/디코딩할 수 있습니다.
여기 pymongo 2.2.1을 사용한 간단한 샘플이 있습니다.
import os
import sys
import json
import pymongo
from bson import BSON
from bson import json_util
if __name__ == '__main__':
try:
connection = pymongo.Connection('mongodb://localhost:27017')
database = connection['mongotest']
except:
print('Error: Unable to Connect')
connection = None
if connection is not None:
database["test"].insert({'name': 'foo'})
doc = database["test"].find_one({'name': 'foo'})
return json.dumps(doc, sort_keys=True, indent=4, default=json_util.default)
ObjectIds에 대응하는 커스텀시리얼라이저를 작성하는 것은 매우 간단합니다.Django에는 이미 소수점 및 날짜를 처리하는 기능이 포함되어 있으므로 다음과 같이 확장할 수 있습니다.
from django.core.serializers.json import DjangoJSONEncoder
from bson import objectid
class MongoAwareEncoder(DjangoJSONEncoder):
"""JSON encoder class that adds support for Mongo objectids."""
def default(self, o):
if isinstance(o, objectid.ObjectId):
return str(o)
else:
return super(MongoAwareEncoder, self).default(o)
이제 넌 알 수 있어json커스텀 시리얼라이저를 사용하려면:
thejson = json.dumps({'results':posts}, cls=MongoAwareEncoder)
Python 3.6에서는 motor==1.1 pymongo==3.4.0을 사용하여 더욱 심플하게 동작합니다.
from bson.json_util import dumps, loads
for mongo_doc in await cursor.to_list(length=10):
# mongo_doc is a <class 'dict'> returned from the async mongo driver, in this acse motor / pymongo.
# result of executing a simple find() query.
json_string = dumps(mongo_doc)
# serialize the <class 'dict'> into a <class 'str'>
back_to_dict = loads(json_string)
# to unserialize, thus return the string back to a <class 'dict'> with the original 'ObjectID' type.
언급URL : https://stackoverflow.com/questions/4404742/how-do-i-turn-mongodb-query-into-a-json
반응형
'programing' 카테고리의 다른 글
| ERROR 404.3 JSON 파일을 찾을 수 없습니다. (0) | 2023.03.15 |
|---|---|
| Web API 이외의 모든 것을 /index.html로 라우팅하는 방법 (0) | 2023.03.15 |
| 표현식에 대한 느린 각 일회성 바인딩 (0) | 2023.03.15 |
| 봄철 웹 소켓 인증 및 인가 (0) | 2023.03.10 |
| AngularJS: ng-read only (0) | 2023.03.10 |