Snake's Home

python解析json

做接口测试的时候,就要对json请求进行解析。

1. python 解析 json

1
2
3
4
5
6
7
8
9
10
import urllib2  
import json

html = urllib2.urlopen(r'http://api.douban.com/v2/book/isbn/9787218087351')

hjson = json.loads(heml.read())

print hjson['rating']
print hjson['images']['large']
print hjson['summary']

2. python 中文乱码的解决:

1
2
3
4
5
6
7
8
9
10
11
12
import sys,codecs, types  
def code():
var1 = "nihao"
var2 = "你好"
print var1
print var2
var2 = var2.decode('utf-8').encode('gbk')
print var2


if __name__ == "__main__":
code()

程序中“你好”默认用UTF-8 编码,程序中先将var2以UTF-8解码再以gbk编码,就可以输出正确的中文

3. python 用httplib发送请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#httplib是Python的http协议的内置,实现模块,使用它可以很简洁的实现http发送请求。   
import httplib
import urllib

#连接服务器

conn=httplib.HTTPConnection('www.python.org')

#发送HTTP请求

conn.request('GET','url')

#得到结果

result=conn.getresponse()

#获取HTTP请求结果值。200为成功

resultStatus=result.status

#获取请求的页面内容

content=result.read()

#关闭连接

conn.close()

#如果要模拟客户端进行请求,可以发送HTTP请求头

headers={"Content-Type":"text/html;charset=gb2312"}

conn.request('POST','url',headers=headers)

#带参数传送

params = urllib.urlencode({'pname':'pvalue'});

conn.request('POST','url',body=params)

发送get 请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python  
#coding=utf8

import httplib

httpClient = None

try:
httpClient = httplib.HTTPConnection('localhost', 80, timeout=30)
httpClient.request('GET', '/test.php')

#response是HTTPResponse对象
response = httpClient.getresponse()
print response.status
print response.reason
print response.read()
except Exception, e:
print e
finally:
if httpClient:
httpClient.close()

发送post请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env python  
#coding=utf8

import httplib, urllib

httpClient = None
try:
params = urllib.urlencode({'name': 'tom', 'age': 22})
headers = {"Content-type": "application/x-www-form-urlencoded"
, "Accept": "text/plain"}

httpClient = httplib.HTTPConnection("localhost", 80, timeout=30)
httpClient.request("POST", "/test.php", params, headers)

response = httpClient.getresponse()
print response.status
print response.reason
print response.read()
print response.getheaders() #获取头信息
except Exception, e:
print e
finally:
if httpClient:
httpClient.close()

实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def httpget(self,url):
httpClient = None
conn = urlparse(url)
url=url.encode('utf-8')
try:
httpClient = httplib.HTTPConnection(conn.netloc, timeout=10)
httpClient.request('GET', url)

response = httpClient.getresponse()
print response
d0=response.read()
d0=d0.decode('unicode_escape')
except Exception, e:
print e
finally:
if httpClient:
httpClient.close()
return response.status,d0



def httppost(self,host,path,params):
httpClient = None
# conn = urlparse(url)
# url=url.encode('utf-8')
try:

body=json.dumps(params)
header = {"Content-type": "application/json", "Accept": "text/plain"}

httpClient = httplib.HTTPConnection(host, timeout=30)
httpClient.request('POST', path, body, header)
response = httpClient.getresponse()
print response.status
#print response.read()

d1=response.read()
#d1=d1.decode('unicode_escape')
d1=json.loads(d1)
except Exception, e:
print e
finally:
if httpClient:
httpClient.close()
return d1