python讀取json文件并將數(shù)據(jù)插入到mongodb的方法
更新時間:2015年03月23日 12:05:25 作者:java潮人
這篇文章主要介紹了python讀取json文件并將數(shù)據(jù)插入到mongodb的方法,實(shí)例分析了Python操作json及mongodb數(shù)據(jù)庫的技巧,需要的朋友可以參考下
本文實(shí)例講述了python讀取json文件并將數(shù)據(jù)插入到mongodb的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
#coding=utf-8
import sunburnt
import urllib
from pymongo import Connection
from bson.objectid import ObjectId
import logging
from datetime import datetime
import json
from time import mktime
from feedparser import _parse_date as parse_date
import time
import sys
import getopt
import ConfigParser
args = sys.argv[1:]
optlist, args = getopt.getopt(args, 'c:')
cmd_opt = {}
for opt in optlist:
cmd_opt[opt[0]] = opt[1]
conf_file = cmd_opt['-c']
config = ConfigParser.ConfigParser()
config.read(conf_file)
hostname = config.get("mongodb", "hostname")
port_num = int(config.get("mongodb", "port_num"))
db_name = config.get("mongodb", "db")
connection = Connection(hostname, port_num)
db = connection[db_name]
courseTable = db.course
lecTable = db.lecture
try:
f = file("json1-14/14.json")
s = json.load(f)
courseData = s["results"]["course"]
lecDataArr = s["results"]["lecture"]
f.close
print "get file content successfully!"
#insert course
courseId = courseTable.save(courseData)
courseId = str(courseId)
print "courseId: "+courseId
print "lec length: "+str(len(lecDataArr))
#insert lecture
lecIdArr = []
for lecData in lecDataArr:
lecData["course_id"] = courseId
lecId = lecTable.save(lecData)
lecIdArr.append(str(lecId))
# update course
courseTable.update({'_id':ObjectId(courseId)},
{"$set":{"lectures.lecture_id_list":lecIdArr}},
upsert=True, multi=True);
print 'insert successfully!'
except Exception, e:
print e
希望本文所述對大家的Python程序設(shè)計有所幫助。
相關(guān)文章
Python OpenCV 彩色與灰度圖像的轉(zhuǎn)換實(shí)現(xiàn)
為了加快處理速度在圖像處理算法中,往往需要把彩色圖像轉(zhuǎn)換為灰度圖像,本文主要介紹了Python OpenCV 彩色與灰度圖像的轉(zhuǎn)換實(shí)現(xiàn),感興趣的可以了解一下2021-06-06
Python+Pygame實(shí)戰(zhàn)之瘋狂吃水果游戲的實(shí)現(xiàn)
吃豆人和切水果這兩個游戲相信大家都不陌生吧,本文將利用Python中的Pygame模塊編寫出一款結(jié)合吃豆人+切水果的新游戲:瘋狂吃水果,感興趣的可以了解一下2022-06-06
已解決不小心卸載pip后怎么處理(重新安裝pip的兩種方式)
這篇文章主要介紹了已解決不小心卸載pip后怎么處理(重新安裝pip的兩種方式),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04
python hbase讀取數(shù)據(jù)發(fā)送kafka的方法
今天小編就為大家分享一篇python hbase讀取數(shù)據(jù)發(fā)送kafka的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
Python實(shí)現(xiàn)打印九九乘法表的不同方法總結(jié)
這篇文章主要為大家介紹了Python實(shí)現(xiàn)打印九九乘法表的幾種不同方法,文中的示例代碼講解詳細(xì),簡潔易懂,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-11-11

