温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-10-23 04:10:08 来源:脚本之家 阅读:187 作者:zhaoyangjian724 栏目:开发技术

如下所示:

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字符串实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI