python 接口返回的json字符串实例

yipeiwu_com5年前Python基础

如下所示:

JSON 函数
使用 JSON 函数需要导入 json 库:import json。

函数	描述
json.dumps	将 Python 对象编码成 JSON 字符串
json.loads	将已编码的 JSON 字符串解码为 Python 对象


#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
import urllib2 
import urllib 
import cookielib
import json
 
def login(): 
 
  data={'username': '015208@zjtlcb.com', 'password': '1234567'}
  post_data=urllib.urlencode(data) #将post消息化成可以让服务器编码的方式 
  cj=cookielib.CookieJar() #获取cookiejar实例 
  opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 
  #自己设置User-Agent(可用于伪造获取,防止某些网站防ip注入) 
  headers = {} 
  website = "http://127.0.0.1:8000/api2/auth-token/"
  req=urllib2.Request(website,post_data,headers) 
  content=opener.open(req) 
  s= content.read() #linux下没有gbk编码,只有utf-8编码
  print s
  print type(s)
  text = json.loads(s)
  print type(text)
  print text['token']
 
if __name__ == '__main__': 
 login() 

C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled/a1.py
{"token": "2c73f3885ac90ee462daea49f1890730f567fbfe"}
<type 'str'>
<type 'dict'>
2c73f3885ac90ee462daea49f1890730f567fbfe

Process finished with exit code 0

以上这篇python 接口返回的json字符串实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python使用tomorrow实现多线程的例子

python使用tomorrow实现多线程的例子

如下所示: import time,requestes from tomorrow import threads @threads(10)#使用装饰器,这个函数异步执行 def d...

python交互式图形编程实例(一)

本文实例为大家分享了python交互式图形编程的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python3# -*- coding: utf-8 -*- #温...

Python 字典(Dictionary)操作详解

Python字典是另一种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型。 一、创建字典 字典由键和对应值成对组成。字典也被称作关联数组或哈希表。基本语法如下:...

解决python3运行selenium下HTMLTestRunner报错的问题

修改HTMLTestRunner.py以支持python3+ 搜索到的结果整理 修改一: 在python shell里输入 >>>import HTMLTestRunn...

python调用java的Webservice示例

一、java端首先我使用的是java自带的对webservice的支持包来编写的服务端和发布程序,代码如下。webservice的接口代码:复制代码 代码如下:package com.x...