python接口如何返回json字符串


本文摘自php中文网,作者小云云,侵删。

本文主要为大家分享一篇python 接口返回的json字符串实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧,希望能帮助到大家。

如下所示:


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

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可以运行在jvm上吗

Python解释器的提示符是什么

Python能做什么?Python爬虫是什么?

Python的元类如何使用

Python如何在图片上添加文字

Python实现各种最优化算法

详细讲解 Python实现对图像进行掩膜遮罩处理

Python如何处理excel数据

Python实现给照片换底色(附代码)

pandas 最详细教程

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...