第三方 API 集成在 Python / Django 中

Third Party API Integration in Python / Django

import requests
r = requests.get('some url')
data = r.text

{"NumberOfPassedStudents":"21061","TotalAttendedCandidates":"74494","NumberOfEnrolledStudents":"84308"}

上面的输出我得到它看起来像 dictionary 但它不是 dictionary 它是 Unicode 。我的问题是我想以下面提到的方式获得输出

Number of Passed Students : 21061
Total Attended Candidates : 74494
Number of Enrolled Students : 84308

python 2.7 中将这些 Unicode 转换为我想要的上述输出的代码是什么。

import re
data={"NumberOfPassedStudents":"21061","TotalAttendedCandidates":"74494","NumberOfEnrolledStudents":"84308"}
for k,v in data.iteritems():
    print re.sub(r"(\w)([A-Z])", r" ",k) +" : "+ v

输出

Number Of Passed Students : 21061
Total Attended Candidates : 74494
Number Of Enrolled Students : 84308

要遍历字典的 key-values 你应该使用 items() 方法:

my_dict = {'a':'foo', 'b':'bar'}
for key, value in my_dict.iteritems():
     print key, value

这会打印

a foo
b bar

对于 CamelCase 的拆分转到

当你有 content-type 的 application/json.

>>> r = requests.get('https://someurl.com')
>>> r.text
u'{"type":"User"...'
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> result = r.json()
>>> result
{u'private_gists': 419, u'total_private_repos': 77, ...}

如果你有其他内容类型,你可以使用json模块将return字符串/unicode转换成pythondict

import json, requests

r = requests.get('some url')
result = json.loads(r.text)

然后您可以通过将结果视为 dict

来获得所需的输出
print 'Number of Passed Students : %s' % result['NumberOfPassedStudents']
print 'Total Attended Candidates : %s' % result['TotalAttendedCandidates']
print 'Number of Enrolled Students : %s' % result['NumberOfEnrolledStudents']