Python將JSON格式數據轉換為SQL語句以便導入MySQL數據庫


        前文中我們把網絡爬蟲爬取的數據保存為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 json

data = []
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 codecs
file_object = codecs.open('tencent.sql', 'w' ,"utf-8")
file_object.write(str)
file_object.close()
print "success"

運行該python腳本。在當前文件夾下將生成一個名為tencent.sql的文件。在phpMyadmin中導入並運行該文件,爬蟲抓取的數據將導入MySQL數據庫。

 






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM