-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhs_code_json_to_xml.py
More file actions
78 lines (62 loc) · 1.87 KB
/
Copy pathhs_code_json_to_xml.py
File metadata and controls
78 lines (62 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/1/10 15:56
# @Author : GuoChang
# @Site : https://github.com/xiphodon
# @File : hs_code_json_to_xml.py
# @Software: PyCharm
# hs编码的json文件,转成xml格式,并存储在SqlServer
import dicttoxml
import json
import pymssql
import settings
import hs_spider
def read_hs_code_json():
"""
读取hs编码的json文件
:return: hs编码字典
"""
with open(hs_spider.hs_code_json_path, 'r', encoding='utf8') as fp:
hs_code_json_dict = json.loads(fp.read())
return hs_code_json_dict
def hs_code_json_to_xml(json_dict):
"""
hs编码的json字典,转成xml字符串
:param json_dict: json字典
:return: xml字符串
"""
return str(dicttoxml.dicttoxml(json_dict, attr_type=False, root=False), encoding='utf8')
def start():
"""
程序入口
:return:
"""
hs_code_json_dict = read_hs_code_json()
conn = pymssql.connect(host=settings.host, user=settings.user, password=settings.password,
database=settings.database_hs_code, charset=settings.charset)
cur = conn.cursor()
if not cur:
raise (NameError, "数据库连接失败")
count = 0
for item_dict in hs_code_json_dict:
item_xml = hs_code_json_to_xml(item_dict)
count += 1
try:
sql_str = "insert into hscode([content]) values(N'%s')" % (item_xml,)
cur.execute(sql_str.encode('utf8'))
conn.commit()
print(count)
except Exception as e:
print(sql_str)
print(e)
conn.close()
def json2xml():
"""
json转xml
:return:
"""
hs_code_json_dict = read_hs_code_json()
xml_str = str(dicttoxml.dicttoxml(hs_code_json_dict, attr_type=False, root=False), encoding='utf8')
if __name__ == '__main__':
start()
# json2xml()