我的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
答案 0 :(得分:2)
json.loads()
函数从字符串加载JSON数据,而您只是给它一个文件名。字符串test.txt
不是有效的JSON字符串。请尝试以下操作从文件加载JSON数据:
with open(testname) as f:
record = json.load(f)
(如果您使用的旧版本的Python不支持with
语句(可能是您使用旧版simplejson
所指示的),那么您必须打开并自己关闭文件。)