Python reads the JSON file and inserts the data into the MongoDB method _python

Source: Internet
Author: User
Tags mongodb

This article describes how Python reads a JSON file and inserts data into MongoDB. Share to everyone for your reference. The implementation method is as follows:

#coding =utf-8 import sunburnt import urllib from Pymongo import Connection from Bson.objectid import objectid import Logg ing from datetime import datetime import JSON to time import mktime from Feedparser import _parse_date as Parse_date Imp ORT time Import sys import getopt import configparser args = sys.argv[1:] optlist, args = getopt.getopt (args, ' C: ') cmd_op t = {} for opt in optlist:cmd_opt[opt[0]] = opt[1] Conf_file = cmd_opt[' c '] config = configparser.configparser () confi G.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.C
  Ourse 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 Lecid ARR = [] 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.lectu
  Re_id_list ": Lecidarr}}, Upsert=true, multi=true); print ' Insert successfully! ' except Exception, E:print E

I hope this article will help you with your 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.