https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13801380000
將get請求json結果轉換爲字典
import json
import urllib
import json
mobile_url='https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13801380000'
#打開一個URL
moblie_res = urllib.urlopen(mobile_url)
#read
res_str=moblie_res.read().decode('gbk').encode('UTF-8')
#print type(res_str) #---> <type 'str'>
# print moblie_res.read().decode('gbk')
# __GetZoneResult_ = {
# mts:'1380138',
# province:'北京',
# catName:'中國移動',
# telString:'13801380000',
# areaVid:'29400',
# ispVid:'3236139',
# carrier:'北京移動'
# }
#寫函數,找到字符串中json開始和結束的索引
def json_start(str_tmp,str_s):
for i in range(0, len(res_str)):
if str_tmp[i]==str_s:
return i
#引用函數
start = json_start(res_str,'{')
end = json_start(res_str,'}')+1
str_tmp =res_str[start:end]
#print str_tmp
#{
# mts:'1380138',
# province:'北京',
# catName:'中國移動',
# telString:'13801380000',
# areaVid:'29400',
# ispVid:'3236139',
# carrier:'北京移動'
# }
#寫函數,去掉字符串中的空格,空行,換行符,及加引號
def delete_space(str_tmp):
new_str = ''
for i in range(0,len(str_tmp)):
#去掉字符串中的空格,空行,換行符
if str_tmp[i]=='{':
new_str = new_str + str_tmp[i]+"\""
elif str_tmp[i]==',':
new_str = new_str + str_tmp[i] + "\""
elif str_tmp[i]==':':
new_str = new_str + "\""+str_tmp[i]
elif str_tmp[i]=='\r':
pass
elif str_tmp[i]==' ':
pass
elif str_tmp[i]=='\n':
pass
elif str_tmp[i]=='\t':
pass
else:
new_str = new_str+str_tmp[i]
#調用函數處理字符串
new_str = delete_space(str_tmp)
print new_str,type(new_str)
#{"mts":'1380138',"province":'北京',"catName":'中國移動',"telString":'13801380000',"areaVid":'29400',"ispVid":'3236139',"carrier":'北京移動'}
#將字符串轉換成json字符串
#res_dict1=json.dumps(new_str)
#print "json:"+res_dict1,type(res_dict1)
#將json 轉換成字典??????
#res_dict=json.loads(res_dict1)
#print "dict:"+res_dict,type(res_dict)
#json:"{\"mts\":'1380138',\"province\":'\u5317\u4eac',\"catName\":'\u4e2d\u56fd\u79fb\u52a8',\"telString\":'13801380000',\"areaVid\":'29400',\"ispVid\":'3236139',\"carrier\":'\u5317\u4eac\u79fb\u52a8'}" <type 'str'>
#dict:{"mts":'1380138',"province":'北京',"catName":'中國移動',"telString":'13801380000',"areaVid":'29400',"ispVid":'3236139',"carrier":'北京移動'} <type 'unicode'>
res_dict=eval(new_str)
print "dict:",res_dict, type(res_dict)
#dict: {'province': '\xe5\x8c\x97\xe4\xba\xac', 'mts': '1380138', 'ispVid': '3236139', 'telString': '13801380000', 'catName': '\xe4\xb8\xad\xe5\x9b\xbd\xe7\xa7\xbb\xe5\x8a\xa8', 'carrier': '\xe5\x8c\x97\xe4\xba\xac\xe7\xa7\xbb\xe5\x8a\xa8', 'areaVid': '29400'} <type 'dict'>