问题
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.
回答1:
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()
回答2:
You forget to add .text
at the end of line lastYearArray = to get the HTML source of the webpage.
Also, I think the last line is not correct...
来源:https://stackoverflow.com/questions/36387302/why-am-i-getting-decoder-errors-when-turning-my-json-array-into-a-python-list-us