1
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.

3 Answers3

4

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']
2ps
  • 15,099
  • 2
  • 27
  • 47
Alex T
  • 4,331
  • 3
  • 29
  • 47
1
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
Cadmus
  • 665
  • 7
  • 13
0

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

Community
  • 1
  • 1
arcegk
  • 1,480
  • 12
  • 15