对json字符串与python字符串的不同之处详解
程序员文章站
2023-10-11 14:55:39
api的应用通常会处理json数据,刚好今天看到了json字符串和python字符串的区别,放一段代码,区别一下子就看出来,的确json 库为处理json 数据提供了不少的...
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网络数据采集)
刚好看到,在貼个库的用法上去,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
以上这篇对json字符串与python字符串的不同之处详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
推荐阅读
-
python实现忽略大小写对字符串列表排序的方法
-
详解.NET中string与StringBuilder在字符串拼接功能上的比较
-
Python对象转JSON字符串的方法
-
Json的概念与Json对象的写法,Json对象与Json字符串转换实例讲解
-
Python3字符串encode与decode的讲解
-
python字符串对其居中显示的方法
-
Python中实现字符串类型与字典类型相互转换的方法
-
对python requests发送json格式数据的实例详解
-
js最实用string(字符串)类型的使用及截取与拼接详解
-
python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)