python URL 处理练习

来源:互联网 发布:php九九乘法表表格 编辑:程序博客网 时间:2024/06/07 04:53

https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13801380000

将get请求json结果转换为字典

import jsonimport urllibimport jsonmobile_url='https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13801380000'#打开一个URLmoblie_res = urllib.urlopen(mobile_url)#readres_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,'}')+1str_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'>

http://www.crifan.com/files/doc/docbook/json_tutorial/release/html/json_tutorial.html

0 0
原创粉丝点击