欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

对json字符串与python字符串的不同之处详解

时间:2021-03-17 09:40:37|栏目:Python代码|点击:

API的应用通常会处理json数据,刚好今天看到了json字符串和python字符串的区别,放一段代码,区别一下子就看出来,的确json 库为处理Json 数据提供了不少的便利。

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 是一个字符串形式的。 没有get方法
#python 字符串有get方法 便于处理 json里面的数据

下面是一段通过ip地址查询地理位置信息的代码,也贴上去,接口是免费的

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网络数据采集)

刚好看到,在?N个库的用法上去,urllib.request.urltrieve 可以根据链接把文件下载下来,上代码好理解一些

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 根据下载链接 可以把文件下载下来

#把logo下载在当前目录,名字叫logo.jpg

上一篇:linux系统使用python获取内存使用信息脚本分享

栏    目:Python代码

下一篇:tensorflow使用神经网络实现mnist分类

本文标题:对json字符串与python字符串的不同之处详解

本文地址:http://www.codeinn.net/misctech/82449.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有