简体   繁体   English

使用pymongo将JSON导入mongoDB

[英]importing JSON to mongoDB using pymongo

i am trying to import a JSON file i pull from a URL and send it to mongoDB as is, using the pymongo module. 我正在尝试导入一个JSON文件,我从URL中提取并使用pymongo模块将其发送到mongoDB。

I have the following code 我有以下代码

#!/usr/bin/env python
import sys, urllib2, json, pymongo
from pymongo import MongoClient
myurl = "https://gist.githubusercontent.com/border/775526/raw/b921df18ba00262ab5bba8cadb3c178e1f7748f7/config.json"
response = urllib2.urlopen(myurl)
data = response.read()
connection = MongoClient('mongodb://user:password@localhost.com:27017/database')
connection.database_names()
db = connection.database
posts = db.posts
post_id = posts.insert_many(data).inserted_id

upon executing this, i get this error raise TypeError("documents must be a non-empty list") TypeError: documents must be a non-empty list 执行此操作时,我得到此错误引发TypeError(“文档必须是非空列表”)TypeError:文档必须是非空列表

ideally, i want to just be able to pull the json from the url and update the mongoDB as this json file will be updated every week. 理想情况下,我希望能够从url中提取json并更新mongoDB,因为这个json文件每周都会更新。 Thanks 谢谢

You need to convert JSON to Python objects, which PyMongo will then convert to BSON for sending to MongoDB. 您需要将JSON转换为Python对象,然后PyMongo将转换为BSON以发送到MongoDB。 To convert JSON to Python objects use the "bson.json_util" module included with PyMongo: 要将JSON转换为Python对象,请使用PyMongo附带的“bson.json_util”模块:

from bson import json_util
data = json_util.loads(response.read())

The standard Python json.loads() function works, too, but PyMongo's json_util.loads() handles some MongoDB-specific details better. 标准的Python json.loads()函数也可以工作,但PyMongo的json_util.loads()可以更好地处理一些MongoDB特定的细节。

You can also use the "requests" library: 您还可以使用“请求”库:

response = requests.get(myurl)
data = response.json()

and post that data to the database. 并将该数据发布到数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM