用Python解析JSON数据
我从GitHub的一个Webhook服务收到了些数据。这些数据包含了关于某个代码库最近提交的信息。我收到的字符串看起来像这样:
payload = {
"ref":"refs/heads/master","commits":[
{"added":[],"author":{"username":"myname","email":"my@email.com","name":"John Doe"},"timestamp":"2011-03-03T02:04:32-08:00","removed":[],"url":"https://github.com/repository/commit/3da6de4ae4550aa84ff16b9b52d8c5179e126dc5","message":"Setup some functions","modified":["apps/api/__init__.py","main.py","utils.py"],"id":"3da6de4ae4550aa84ff16b9b52d8c5179e126dc5"}
],
"compare":"https://github.com/repository/compare/a270fe9...eb26a23","after":"eb26a2312e1955ccb2b7cb50d43682be87c30faa","repository":{"pushed_at":"2011/03/03 02:23:14 -0800","has_issues":true,"has_downloads":true,"url":"https://github.com/repository","watchers":1,"fork":false,"has_wiki":true,"private":false,"size":2248,"forks":1,"created_at":"2011/02/23 04:41:51 -0800","owner":{"email":"my@email.com","name":"john"},"name":"john","language":"Python","open_issues":0},"forced":false,"before":"a270fe954359caa323a9880afc3d6301055ea566"
}
我想知道怎么才能正确地去掉那个变量 payload=
,只保留 {}
之间的数据,这样才能得到一个可以用 simplejson
解析的正确JSON格式。现在我只是用 json_data = json_data.replace('payload=', '')
来处理这个问题。但我不确定这样做是否正确。有没有更好的方法呢?谢谢。
更新 我在GitHub的支持论坛上发了一条 消息,描述了这个问题。
2 个回答
1
其实没有一种“正确”的方法来处理这个问题,除非你打算自己写一个完整的JavaScript解析器。不过,Thomas建议的解决方案更通用一些,比如说如果GitHub以后改了文件格式,或者你用在其他数据源上,它出错的可能性就会小很多。
6
我会寻找第一个 { 字符:
jsondata = jsondata[jsondata.index("{"):]