[英]Error retrieving json data from external url and saving to mongoDB in python
我需要幫助將從外部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
read()給您一個字符串,而不是jsonobject。 您必須自己解析。
我認為請求庫對此更好:
import requests
jsonobject = requests.get('url').json()
這是te docs: http : //docs.python-requests.org/en/latest/
我認為您的test
變量是字符串,對嗎?
您必須轉換json
格式。 它應該是json格式。
import json
test = '[{"_id" : 1, "name" : "HELLO"}, {"_id" : 2, "name" : "Happy"}]'
db.Collection.save(json.loads(test))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.