Python將JSON格式資料轉換為SQL語句以便匯入MySQL資料庫

來源:互聯網
上載者:User

標籤:指令碼   ati   detail   oca   value   get   sts   data   target   

        前文中我們把網路爬蟲爬取的資料儲存為JSON格式,但為了能夠更方便地處理資料。我們希望把這些資料匯入到MySQL資料庫中。phpMyadmin能夠把MySQL資料庫中的資料匯出為JSON格式檔案,但卻不能把JSON格式檔案匯入到MySQL資料庫。為了實現這個目標,能夠編寫Python指令碼將JSON格式資料轉換為SQL語句以便匯入MySQL資料庫。


JSON檔案tencent.json部分內容:

{"recruitNumber": "1", "name": "SD10-FPS俄語遊戲海外PM(深圳)", "detailLink": "http://hr.tencent.com/position_detail.php?id=9587&keywords=&tid=0&lid=0", "publishTime": "2013-11-13", "catalog": "產品/項目類", "workLocation": "深圳"}
{"recruitNumber": "2", "name": "HY2-互動娛樂遊戲網遊財產安全運營專員(深圳)", "detailLink": "http://hr.tencent.com/position_detail.php?id=9482&keywords=&tid=0&lid=0", "publishTime": "2013-11-28", "catalog": "產品/項目類", "workLocation": "深圳"}


在phpMyadmin中建立資料庫及表結構:

CREATE DATABASE itzhaopin;

CREATE TABLE IF NOT EXISTS `tencent` (  `id` int(11) NOT NULL auto_increment,  `name` varchar(512)  default NULL,  `catalog` varchar(64) default NULL,  `workLocation` varchar(64) default NULL,  `recruitNumber` varchar(64) default NULL,  `detailLink` varchar(1024) default NULL,  `publishTime` varchar(64) default NULL,  PRIMARY KEY (`ID`)) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

編寫Python指令碼json2sql.py將JSON格式資料轉換為SQL語句:

#-*- coding: UTF-8 -*-import jsondata = []with open(‘itzhaopin/tencent.json‘) as f:    for line in f:        data.append(json.loads(line))#print json.dumps(data, ensure_ascii=False)str = "\r\n"for item in data:    #print json.dumps(item)    str = str + "insert into tencent(name,catalog,workLocation,recruitNumber,detailLink,publishTime) values "    str = str + "(‘%s‘,‘%s‘,‘%s‘,‘%s‘,‘%s‘,‘%s‘);\r\n" % (item[‘name‘],item[‘catalog‘],item[‘workLocation‘],item[‘recruitNumber‘],item[‘detailLink‘],item[‘publishTime‘])import codecsfile_object = codecs.open(‘tencent.sql‘, ‘w‘ ,"utf-8")file_object.write(str)file_object.close()print "success"

運行該python指令碼。在當前檔案夾下將產生一個名為tencent.sql的檔案。在phpMyadmin中匯入並運行該檔案,爬蟲抓取的資料將匯入MySQL資料庫。

 





Python將JSON格式資料轉換為SQL語句以便匯入MySQL資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.