python, json, xml的转换

今天在做数据处理时用到了百度地图API,结合Geopy来做地点的定位,当然需要坐标啦。

可惜的是,作为新手我没注意到百度返回的是xml,需要转换成json,然后在转换成Python里的字典(dict),方便嵌套引用。百度返回的是个这样的字符串,但是打开url返回的没有第一行header。开始我以为是header问题,还把第一行去掉了,其实是多此一举。

<?xml version="1.0" encoding="utf-8" ?> 
<GeocoderSearchResponse> 
	<status>OK</status>
	<result>
					<location>
				<lat>37.195699</lat>
				<lng>122.096751</lng>
			</location>	
			<precise>0</precise>
			<confidence>30</confidence>
			<level>道路</level>
			</result>	
</GeocoderSearchResponse>
<GeocoderSearchResponse> 
	<status>OK</status>
	<result>
					<location>
				<lat>37.195699</lat>
				<lng>122.096751</lng>
			</location>	
			<precise>0</precise>
			<confidence>30</confidence>
			<level>道路</level>
			</result>	
</GeocoderSearchResponse>

这个xml可以尝试在 https://www.json.cn/# 进行转换(转换成json的dict格式),如果成功说明数据没问题。在python里可以用xmltodict这个第三方包来把xml转换成json(到了这里离我们所需要的Pythondict就是咫尺之遥了):

{
 "GeocoderSearchResponse": {
  "status": "OK",
  "result": {
   "location": {
    "lat": "37.195699",
    "lng": "122.096751"
   },
   "precise": "0",
   "confidence": "30",
   "level": "\u9053\u8def"
  }
 }
}

最后,需要把上面的json用json.loads转换成python里的dict:

{'GeocoderSearchResponse': {'status': 'OK', 'result': {'location': {'lat': '37.195699', 'lng': '122.096751'}, 'precise': '0', 'confidence': '30', 'level': '道路'}}}

到了这里你就能方便地索引了,比如索引这里的lat(dict就是层层嵌套):

print(json_dict['GeocoderSearchResponse']['result']['location']['lat'])

项目完成后再把源码放到github上,参考:

https://blog.csdn.net/qq_39247153/article/details/81984524

https://www.cnblogs.com/chenfulin5/p/7834466.html

(json的用法)

https://blog.csdn.net/JOJOY_tester/article/details/71435935 (介绍xml2dict)

跑代码的时候又发现数据的另外一个问题,个别医院的地址栏竟然有两个地址,分号分开的!程序就崩溃了。如下:

mysql> SELECT * FROM top_tier3_hospital WHERE address LIKE "%北京市东城区天坛西里4号%";
+------------------------------+---------------+-----------+--------+---------------------------------------------------------------------+----------------------------------------+
| hospital_name_new            | hospital_tier | Provinces | Cities | address                                                             | phone                                  |
+------------------------------+---------------+-----------+--------+---------------------------------------------------------------------+----------------------------------------+
| 首都医科大学附属北京口腔医院 | 三级甲等      | 北京市    | 东城区 | 北京市东城区天坛西里4号(天坛);北京市东城区锡拉胡同11号(王府井) | 010-67099114(总机);67099284(咨询) |
+------------------------------+---------------+-----------+--------+---------------------------------------------------------------------+----------------------------------------+
1 row in set (0.00 sec)

发表评论