炎热的夏天过去了,凉爽的秋天来了。它是一个收获的季节,也是各种水果最多的时候,红艳艳的苹果扒开绿叶往外瞧;小红灯笼似的枣子挂满枝头;像紫玛瑙的葡萄一串串地挂在葡萄架下,真迷人呀!
本文实例讲述了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读取json文件并将数据插入到mongodb的方法就介绍到这了。世上没有一件工作不辛苦,没有一处人事不复杂。在外很不容易,努力过后才知道许多事情,坚持坚持就过来了,一觉醒来又是满血复活的一天。更多相关python读取json文件并将数据插入到mongodb的方法内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!