python读取json文件并将数据插入到mongodb的方法

yipeiwu_com5年前Python基础

本文实例讲述了python读取json文件并将数据插入到mongodb的方法。分享给大家供大家参考。具体实现方法如下:

#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程序设计有所帮助。

相关文章

python中的reduce内建函数使用方法指南

官方解释: Apply function of two arguments cumulatively to the items of iterable, from left to r...

python实现将一维列表转换为多维列表(numpy+reshape)

如题,我们直接使用numpy #!D:/workplace/python # -*- coding: utf-8 -*- # @File : numpy_reshape.py # @...

python实现微信发送邮件关闭电脑功能

Python 通过微信邮件实现电脑关机,供大家参考,具体内容如下 通过手机微信发送QQ邮件给sina邮箱,然后利用python的pop3定时检查sina邮箱的邮件主题以及邮件来源,并在电...

Tensorflow实现卷积神经网络的详细代码

本文实例为大家分享了Tensorflow实现卷积神经网络的具体代码,供大家参考,具体内容如下 1.概述 定义: 卷积神经网络(Convolutional Neural Network,...

python检查序列seq是否含有aset中项的方法

本文实例讲述了python检查序列seq是否含有aset中项的方法。分享给大家供大家参考。具体实现方法如下: # -*- coding: utf-8 -*- def contains...