Samresh Kumar Jha
Samresh Kumar Jha

Reputation: 55

Third Party API Integration in Python / Django

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

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

The above output I got it looks like a dictionary but it is not a dictionary it is a Unicode . My question is I want to get output in the below mention way

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

What is the code in python 2.7 to convert those Unicode into my desire above mention output.

Upvotes: 1

Views: 8287

Answers (3)

Alex T
Alex T

Reputation: 4659

You can use the in-built json() method to convert your HTTP response data to a python dict when you have a content-type of 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, ...}

If you have another content type, you can use the json module to convert the return string / unicode into a python dict

import json, requests

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

Then you can get your desired output by treating your result as a dict

print 'Number of Passed Students : %s' % result['NumberOfPassedStudents']
print 'Total Attended Candidates : %s' % result['TotalAttendedCandidates']
print 'Number of Enrolled Students : %s' % result['NumberOfEnrolledStudents']

Upvotes: 4

arcegk
arcegk

Reputation: 1480

To iterate over a dict's key-values you should use items() method:

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

this prints

a foo
b bar

for split that CamelCase go to this answer

Upvotes: 0

Cadmus
Cadmus

Reputation: 665

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

output

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

Upvotes: 1

Related Questions