AttributeError:'str'对象没有属性'read'Python ..

时间:2017-03-18 20:52:04

标签: python json

以下是代码:

import urllib, json, unicodedata, webbrowser

url = "https://en.wikipedia.org/w/api.php?action=query&list=random&rnnamespace=0&rnlimit=10&format=json"



response = urllib.urlopen(url)
data = json.loads(response.read())
while True:
    if data.get("data") == None:
        print "server error, trying again"
        data = json.loads(response.read())
    else:
        break

for a in data["query"]["random"]:
    print a["title"]
    userread = raw_input("Would you like to read this article? y/n")
    if userread.lower() == "y":
        articleid = a["id"]
        articleurl = "https://en.wikipedia.org/?curid=" + articleid
        webbrowser.open_new(articleurl)

现在,for循环并不重要,因为我遇到了这个错误:

  File "randomwiki.py", line 12, in <module>
    data = json.loads(response.read())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

网址是维基百科在JSON中的随机页面文章API。我不确定是什么问题。有帮助吗?

1 个答案:

答案 0 :(得分:0)

您从json.loads函数接收一个字节对象,但requests收到字符串。 如果需要,您可以使用import requests response = requests.get(url) data = json.loads(response.read()) 模块:

urllib.read

或者,您当然可以解码data = json.loads(response.read().decode()) 函数的输出。

private void button1_Click(object sender, EventArgs e) // --- Add ---
    {
        unit = new Unit(textBox1.Text, int.Parse(textBox2.Text), int.Parse(textBox3.Text), int.Parse(textBox4.Text),
                                            int.Parse(textBox5.Text), int.Parse(textBox6.Text), int.Parse(textBox7.Text),
                                            int.Parse(textBox8.Text), int.Parse(textBox9.Text), int.Parse(textBox10.Text), 
                                            int.Parse(textBox11.Text), textBox2.Text);
        unitList.AddUnit(unit);
        XmlSerialization.WriteToXmlFile<UnitList>("List.xml", unitList);
...