Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

Why am I getting decoder errors when turning my JSON array into a Python list using json.loads?

Below is the error code I received on my Terminal call of "python lastYearArray.py". (I'm on a MacBook Pro running OSX 10.9.5, editing my Python program in jEdit). According to this link: TypeError: expected string or buffer it appears that the function I am using doesn't take lists either. I would just be working with the JSON file instead of converting it, but this particular JSON data has no headers or element tags, such as "fruits: apple, banana, orange"; it only has a long string of numbers separated by commas and braces.

Traceback (most recent call last):
      File "lastYearAnalysis.py", line 8, in <module>
        PyListData = json.loads(lastYearArray)
      File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads
        return _default_decoder.decode(s)
      File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
        obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    TypeError: expected string or buffer

However,I don't know why it is telling me about a decoder, because as you can see from my rather minimal code here:

#Write json array to a python list to find the iterative location of max value
#should return a value such as "[n]" on req for max

import requests
import json

lastYearArray = requests.get('https://api.github.com/repos/mbostock/d3/stats/contributors')
PyListData = json.loads(lastYearArray)
print data[PyListData]

#TODO: ask for max value

I'm not using an explicit decoder function that I can see; I'm using json.loads. I should add that I am certainly a Python novice with regards to lists and JSON array decoding. Any info, however basic, that you can provide would be immensely helpful to me.

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

requests.get returns a Response object. That object is not a string object, so you cannot pass it to json.loads.

You have to get the response object’s using response.text, and pass that to json.loads:

lastYearArrayResponse = requests.get('…')
data = json.loads(lastYearArrayResponse.text)

Alternatively, you can also use the response.json() method to get the parsed response since requests already comes with built-in support for JSON responses:

lastYearArrayResponse = requests.get('…')
data = lastYearArrayResponse.json()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...