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

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

刚好看到,在貼个库的用法上去,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设计】。

相关文章

django使用haystack调用Elasticsearch实现索引搜索

django使用haystack调用Elasticsearch实现索引搜索

前言: 在做一个商城项目的时候,需要实现商品搜索功能。 说到搜索,第一时间想到的是数据库的 select * from tb_sku where name like %苹果手机% 或者...

Python线程障碍对象Barrier原理详解

python线程Barrier俗称障碍对象,也称栅栏,也叫屏障。 一.线程障碍对象Barrier简介 # 导入线程模块 import threading # 障碍对象barrier...

python3 实现对图片进行局部切割的方法

python3 实现对图片进行局部切割的方法

先拿个图片举例子,比如说截取途中方框内的图片: # 导入相关的库 from PIL import Image # 打开一张图 img = Image.open('test.jpg'...

python TKinter获取文本框内容的方法

如下所示: #coding:utf-8 import urllib,urllib2 import Tkinter #导入TKinter模块 ytm=Tkinter.Tk() #创...

对python中的高效迭代器函数详解

对python中的高效迭代器函数详解

python中内置的库中有个itertools,可以满足我们在编程中绝大多数需要迭代的场合,当然也可以自己造轮子,但是有现成的好用的轮子不妨也学习一下,看哪个用的顺手~ 首先还是要先im...