如何将从 psycopg2 查询返回的有效 json 字符串转换为可以通过 pymongo 插入到 mongo 实例的 json?我尝试了很多事情,但都没有成功。我在插入 mongo 时不断收到 TypeError TypeError: 'str' object does not support item assignment
。
顺便说一下,我正在使用 Python 2.7 和 psycopg2 2.4.5,以及 pymongo 2.1。如有必要,我可以升级,我只是使用默认安装的 Ubuntu 和 apt-get。
import psycopg2
import pymongo
from pymongo import Connection
import ast
import json
connection = Connection()
db = connection['af_reports_test']
psa = db['psa']
cur = con.cursor()
cur.execute("SELECT activity_json FROM \"edus\".\"ACTIVITIES\" WHERE status='PUBLISHED'")
results = cur.fetchall()
for rec in results:
for value in rec:
psa.insert(value)
这是我从数据库中返回的示例:
{"activity":{"to":{"users":["someone","someoneElse"]}}}
另外,这是回溯:
Traceback (most recent call last):
File "getPSA.py", line 33, in <module>
psa.insert(activity)
File "/usr/lib/python2.7/dist-packages/pymongo/collection.py", line 300, in insert
docs = [self.__database._fix_incoming(doc, self) for doc in docs]
File "/usr/lib/python2.7/dist-packages/pymongo/database.py", line 252, in _fix_incoming
son = manipulator.transform_incoming(son, collection)
File "/usr/lib/python2.7/dist-packages/pymongo/son_manipulator.py", line 73, in transform_incoming
son["_id"] = ObjectId()
TypeError: 'str' object does not support item assignment