Django에서 pymongo로 DB 조회해서 for문으로 돌리며 추가 값을 할당하는 로직을 구현하려고 한다. 아래와 같이 하면 될 것 같으나 잘 안 된다.
result = dbname['test'].find()
for val in result:
val['addData'] = 1111
print(result)
//error
//TypeError: <pymongo.cursor.Cursor object at 0x7fea1c3183d0> is not JSON serializable
이것저것 해보다가 그다지 신뢰가 안 가지만 chatGPT에게 물어봤다.
소스는 내가 짠 거랑 비슷한데 여전히 에러가 난다.
TypeError: Object of type Cursor is not JSON serializable
그래서 이번엔 에러 코드로 물어봤다.
오홋. 된다.
DB 결과물은 cursor 객체인데 이를 json으로 변경하려면 안 된다는 얘기. 그래서 list 객체를 만들어 cursor 객체를 복사한 후 list 객체에 추가 값을 할당하고 이를 json 으로 리턴해야 하는 것.
처음으로 chatGPT로 도움을 얻었다. 질문을 여러번 해야 원하는 결과값에 도달하는 듯 하다.
- list 객체: 데이터를 대괄호로 묶은 것
chatGPT의 결과물
import pymongo
import json
# MongoDB와 연결
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["mycollection"]
# MongoDB에서 데이터 가져오기
results = collection.find()
# Python 리스트에 데이터 저장
data = []
for result in results:
data.append(result)
# Python 객체에 새로운 key-value 쌍 추가
for d in data:
d["new_key"] = "new_value"
# Python 객체를 json으로 직렬화
json_results = json.dumps(data)
# 결과 출력
print(json_results)