1

I m trying to parse github using python, but its throwing the exception

the JSON object must be str, not 'bytes'

def profile(request):
    jsonList = []
    req = requests.get('https://api.github.com/users/DrkSephy')
    jsonList.append(json.loads(req.content))
    parsedData = []
    userData = {}
    for data in jsonList:
        userData['name'] = data['name']
        userData['blog'] = data['blog']
        userData['email'] = data['email']
        userData['public_gists'] = data['public_gists']
        userData['public_repos'] = data['public_repos']
        userData['avatar_url'] = data['avatar_url']
        userData['followers'] = data['followers']
        userData['following'] = data['following']
    parsedData.append(userData)
    return HttpResponse(str(parsedData, 'utf-8'))

How to solve it, i m using python 3.5.1 and Django 1.9.6

rj978281
  • 11
  • 1
  • 4
  • Apart from the `req.content` issue, you are also using dictionaries incorrectly. You are updating the *same, single dictionary* each time in your loop, so in the end `parsedData` will have N references to one dictionary, and that dictionary will only hold the information from the last `data` entry. – Martijn Pieters May 19 '16 at 19:55
  • Then, you are also returning the `parsedData` list as a *Python repr()` string*. Are you sure that that is what your web server should be serving? If you want to send JSON back, you really want to use `json.dumps()` instead. – Martijn Pieters May 19 '16 at 19:56
  • You also added the JSON result as **one** element into the `jsonList`, then iterate over this list. Why do this at all? Why not just copy directly from the dictionary decoded from the `JSON` response? – Martijn Pieters May 19 '16 at 20:02

1 Answers1

4

You need to call .text, .content in python3 returns bytes:

 jsonList.append(json.loads(req.text))

But you don't need json.loads at all, you can simply call .json() directly using requests:

 jsonList.append(req.json())
Padraic Cunningham
  • 160,756
  • 20
  • 201
  • 286