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.