欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

對(duì)json字符串與python字符串的不同之處詳解

 更新時(shí)間:2018年12月19日 10:25:12   作者:子灬丶逾  
今天小編就為大家分享一篇對(duì)json字符串與python字符串的不同之處詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

API的應(yīng)用通常會(huì)處理json數(shù)據(jù),剛好今天看到了json字符串和python字符串的區(qū)別,放一段代碼,區(qū)別一下子就看出來,的確json 庫為處理Json 數(shù)據(jù)提供了不少的便利。

import json

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 是一個(gè)字符串形式的。 沒有g(shù)et方法
#python 字符串有g(shù)et方法 便于處理 json里面的數(shù)據(jù)

下面是一段通過ip地址查詢地理位置信息的代碼,也貼上去,接口是免費(fèi)的

import json
from urllib.request import urlopen

def getCountry(ipAddress):

 response = urlopen("http://freegeoip.net/json/"+ipAddress).read().decode('utf-8')

 responseJson = json.loads(response)
 print(responseJson)
 return responseJson.get("country_code")


print(getCountry("50.78.253.58"))

(代碼來自python網(wǎng)絡(luò)數(shù)據(jù)采集)

剛好看到,在貼個(gè)庫的用法上去,urllib.request.urltrieve 可以根據(jù)鏈接把文件下載下來,上代碼好理解一些

from urllib.request import urlretrieve
from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen('http://www.pythonscraping.com')

bs4 = BeautifulSoup(html,'xml')

imageLocation = bs4.find("a",{"id":"logo"}).find("img")['src']

urlretrieve(imageLocation,"logo.jpg") #urlretrieve 根據(jù)下載鏈接 可以把文件下載下來

#把logo下載在當(dāng)前目錄,名字叫l(wèi)ogo.jpg

以上這篇對(duì)json字符串與python字符串的不同之處詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論