Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

python - JSON serializing Mongodb

I am using the python package pymongo to retrieve data from a mongodb database.

>>> r = collection.find()   # returns an object of class 'Cursor'

Then I convert to a list

>>> l = list(r)             # returns a 'list' of 'dict'

here is what print(l) returns:

>>> [{u'date': datetime.datetime(2009, 11, 10, 10, 45), u'_id': 1, u'name': u'name1', u'value': 11},{u'date': datetime.datetime(2013, 11, 10, 10, 45), u'_id': 2, u'name': u'name2', u'value': 22}]

Now I need to convert to JSON so that I can manipulate it.

>>> json.dumps(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python2.7/json/encoder.py", line 201, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python2.7/json/encoder.py", line 264, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python2.7/json/encoder.py", line 178, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.datetime(2009, 11, 12, 11, 14) is not JSON serializable

I have also tried to follow http://api.mongodb.org/python/1.7/api/pymongo/json_util.html without success: Edit: the recent version of the link is http://api.mongodb.org/python/current/api/bson/json_util.html

>>> json.dumps(l, default=json_util.default)  
Traceback (most recent call last):  
  File "<stdin>", line 1, in <module>  
NameError: name 'json_util' is not defined  

Note: precisely I need to push this result to R using the R package rPython and its function rPython::python.get("l")

Side Question: What is the u (u'Date', u'name', etc..) before each field in the list of dict?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The pymongo documentation you pointed is obsolete. If you're using version 1.7 I recommend updating. With a more recent version you can do this:

from bson.json_util import dumps

dumps(l)

http://api.mongodb.org/python/current/api/bson/json_util.html

Side answer: u'name', u'date', u'_id' etc are the names of the fields of the document on the database.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...