对json字符串与python字符串的不同之处详解
API的应用通常会处理json数据,刚好今天看到了json字符串和python字符串的区别,放一段代码,区别一下子就看出来,的确json库为处理Json数据提供了不少的便利。
importjson
jsonString='{"arrayOfNums":[{"number":0},{"number":1},{"number":2}],"arrayOfFruits":[{"fruit":"apple"},{"fruit":"banana"},{"fruit":"pear"}]}'
jsonObj=json.loads(jsonString)
print(jsonObj.get("arrayOfNums"))
print(jsonObj.get("arrayOfNums")[0].get('number'))
#json是一个字符串形式的。没有get方法
#python字符串有get方法便于处理json里面的数据
下面是一段通过ip地址查询地理位置信息的代码,也贴上去,接口是免费的
importjson
fromurllib.requestimporturlopen
defgetCountry(ipAddress):
response=urlopen("http://freegeoip.net/json/"+ipAddress).read().decode('utf-8')
responseJson=json.loads(response)
print(responseJson)
returnresponseJson.get("country_code")
print(getCountry("50.78.253.58"))
(代码来自python网络数据采集)
刚好看到,在貼个库的用法上去,urllib.request.urltrieve可以根据链接把文件下载下来,上代码好理解一些
fromurllib.requestimporturlretrieve
fromurllib.requestimporturlopen
frombs4importBeautifulSoup
html=urlopen('http://www.pythonscraping.com')
bs4=BeautifulSoup(html,'xml')
imageLocation=bs4.find("a",{"id":"logo"}).find("img")['src']
urlretrieve(imageLocation,"logo.jpg")#urlretrieve根据下载链接可以把文件下载下来
#把logo下载在当前目录,名字叫logo.jpg
以上这篇对json字符串与python字符串的不同之处详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。