gpt4 book ai didi

python - 在python中从外部url检索json数据并保存到mongoDB时出错

转载 作者:太空宇宙 更新时间:2023-11-03 18:04:58 25 4
gpt4 key购买 nike

我需要帮助将从外部 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。你必须自己解析它。

我认为 requests 库更适合这个:

import requests

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

以下是文档:http://docs.python-requests.org/en/latest/

关于python - 在python中从外部url检索json数据并保存到mongoDB时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27056063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com