Python method for reading JSON files and inserting data into MongoDB

Source: Internet
Author: User
The example in this article describes how Python reads the JSON file and inserts the data into MongoDB. Share to everyone for your reference. The 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_dateimpo RT Timeimport Sysimport Getoptimport Configparserargs = sys.argv[1:]optlist, args = getopt.getopt (args, ' C: ') cmd_opt = {}f or 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"] l  Ecdataarr = 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:lec data["course_id"] = CourseID lecid = Lectable.save (lecdata) lecidarr.append (str (LECID)) # Update Course COURSETABL E.update ({' _id ': ObjectId (CourseID)}, {"$set": {"lectures.lecture_id_list": Lecidarr}}, Upsert=true, mu  Lti=true); print ' Insert successfully! ' Except Exception, E:print E

Hopefully 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.