2014-11-21 47 views
1

我需要幫助將從外部URL檢索到的json數據保存到python中的MongoDB。 我寫下來的代碼片段粘貼在下面。任何幫助將不勝感激。我在這個網站上是新的。錯誤從外部URL檢索json數據並保存到Python中的mongoDB

import urllib.request 

import pymongo 

client = pymongo.MongoClient("localhost",27017) 

db = client.test_database #database where I intend to store data 

Collection = db.samplecollection # documents collection 
#read data from url 
readData = urllib.request.urlopen('some url that returns json data') 
#store the data read to a variable (I don't know if a document in Mongo is equivalent to an object or a complex type) 
test = readData.read() # I confirmed data is being read 
#save data to MongoDB 
db.Collection.save(test) # when I try to save data to mongoDB I get an error 

''' 
Error message 
Traceback (most recent call last): 
    File "C:\EzempilloPythonScripts\readFdaData.py", line 8, in <module> 
    db.Collection.save(test) 
    File "C:\Python34\lib\site-packages\pymongo\collection.py", line 282, in save 
    raise TypeError("cannot save object of type %s" % type(to_save)) 
TypeError: cannot save object of type <class 'bytes'> 
''' 

print (test) # I can print the data 

回答

0

我想你的test變量是一個字符串吧?

您必須轉換json格式。它應該是json格式。

import json 
test = '[{"_id" : 1, "name" : "HELLO"}, {"_id" : 2, "name" : "Happy"}]' 
db.Collection.save(json.loads(test)) 
1

read()給你一個字符串,而不是一個jsonobject。你必須自己解析它。

我想請求lib是這更好:

import requests 

jsonobject = requests.get('url').json() 

這裏是TE文檔: