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 Answers 3

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']
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

my output looks like dictionary but it is a unicode.
convert unicode object in to json using json.loads(), then process the dictionary
Get the key from the dictionary and find the capital letter occurrences from the key string and consider it as word starting then adding the space.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.