python - 使用 simplejson 在 Python 中解码来自 Twitter 的 JSON 文件

标签 python json twitter

我的 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

生成了该文件

最佳答案

json.loads() 函数从字符串加载 JSON 数据,您只需为其指定一个文件名。字符串 test.txt 不是有效的 JSON 字符串。尝试以下方法从文件加载 JSON 数据:

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

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

关于python - 使用 simplejson 在 Python 中解码来自 Twitter 的 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12772626/

相关文章:

objective-c - iOS6 - 社交框架 - SLComposeViewController 如何回退到 iOS5 的 TWTweetComposeViewController?

使用 format 命令进行 python 字符串操作

python - "python"未被识别为命令

javascript - 计算对象数组上的所有值 - javascript

javascript - ReactJS中点击按钮时如何动态显示html内容?

python - Twitter Stream API,参数跟随有无法解析的项目

Python父类访问子类的类变量

Python 2.7 : Code won't return answer - someone explain why?

javascript - 如何解决 Access-Control-Allow-Origin 错误?

html - 删除菜单和轮播之间的空格 Twitter bootstrap 2.2.2