Python reads json files and inserts data into mongodb,

Source: Internet
Author: User

Python reads json files and inserts data into mongodb,

This example describes how python reads json files and inserts data into mongodb. Share it with you for your reference. The specific implementation method is as follows:

#coding=utf-8import sunburntimport urllibfrom pymongo import Connectionfrom bson.objectid import ObjectIdimport loggingfrom datetime import datetimeimport jsonfrom time import mktimefrom feedparser import _parse_date as parse_dateimport timeimport sysimport getoptimport ConfigParserargs = 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.courselecTable = db.lecturetry:  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

I hope this article will help you with Python programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.