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.