2

我的 JSON 文件的一小部分如下所示。它通过了一个 JSON 验证器。(我添加了 cl

{
"next_page": "?page=2&max_id=210389654296469504&q=cocaine&geocode=40.665572%2C-73.923557%2C10mi&rpp=100",
"completed_in": 0.289,
"max_id_str": "210389654296469504",
"since_id_str": "0",
"refresh_url": "?since_id=210389654296469504&q=cocaine&geocode=40.665572%2C-73.923557%2C10mi",
"results": [
    {
        "iso_language_code": "en",
        "to_user_id": 486935435,
        "to_user_id_str": "486935435",
        "profile_image_url_https": "https://si0.twimg.com/profile_images/1561856049/Zak_W_Photo_normal.jpg",
        "from_user_id_str": "82389940",
        "text": "@Bill__Murray cocaine > productivity! Last night I solved the euro crisis and designed a new cat. If I could only find that napkin.",
        "from_user_name": "Zak Williams",
        "in_reply_to_status_id_str": "210319741322133504",
        "profile_image_url": "http://a0.twimg.com/profile_images/1561856049/Zak_W_Photo_normal.jpg",
        "id": 210389654296469500,
        "to_user": "Bill__Murray",
        "source": "<a href="http://twitter.com/#!/download/iphone" rel="nofollow">Twitter for iPhone</a>",
        "in_reply_to_status_id": 210319741322133500,
        "to_user_name": "Bill Murray",
        "location": "Brooklyn",
        "from_user": "zakwilliams",
        "from_user_id": 82389940,
        "metadata": {
            "result_type": "recent"
        },
        "geo": "null",
        "created_at": "Wed, 06 Jun 2012 15:16:17 +0000",
        "id_str": "210389654296469504"
    }
]
}

当我尝试通过键入以下代码在 Python 中加载它时,我收到以下错误。

代码

 import simplejson as json
 testname = 'test.txt'
 record = json.loads(testname)

错误

 raise JSONDecodeError("No JSON object could be decoded", s, idx)
 simplejson.decoder.JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)

我究竟做错了什么?实际上,我通过使用生成了文件simplejson.dump

4

1 回答 1

2

该函数从stringjson.loads()加载 JSON 数据,而您只是给它一个文件名。该字符串不是有效的 JSON 字符串。尝试以下方法从文件加载 JSON 数据:test.txt

with open(testname) as f:
    record = json.load(f)

(如果您使用的是不支持该with语句的旧版本的 Python(如您使用 old 可能表明的那样simplejson),那么您必须自己打开和关闭文件。)

于 2012-10-07T20:34:44.230 回答