2011-03-03 152 views
2

我从GitHub的网络挂接服务接收的一些数据。它包含有关仓库中最近提交的信息。字符串我收到这个样子的:解析JSON数据与Python

payload = { 
    "ref":"refs/heads/master","commits":[ 
     {"added":[],"author":{"username":"myname","email":"[email protected]","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":"[email protected]","name":"john"},"name":"john","language":"Python","open_issues":0},"forced":false,"before":"a270fe954359caa323a9880afc3d6301055ea566" 
} 

什么是去除变量payload=并获得唯一{}之间的数据,因此,这将是一个正确的JSON,我可以simplejson解析正确的方式?现在我只使用json_data = json_data.replace('payload=', '')。我不确定这是做这件事的正确方法。我怎样才能做得更好?谢谢。

UPDATE 我在GitHub支持板上发布了一个message问题描述。

+3

这也可能是值得窃听Github上返回有效JSON - 它可能是在其末端的一个错误。 – 2011-03-03 13:19:38

+0

你怎么收到它?它是在HTTP响应中还是在HTTP中? – 2011-03-03 14:03:44

+0

GitHub发送POST到我在设置中提供的URL。这里描述:http://help.github.com/post-receive-hooks/。所以,它在我的问题中发送一个带有字符串的POST。 – 2011-03-03 14:12:50

回答

6

我会找第一个字符{:

​​
+0

完美的作品,谢谢! – 2011-03-03 15:19:39

1

有这样做,除非你想实现一个完整的JS解析器没有单一的“正确”的方式。也就是说,Thomas提出的解决方案更具概括性,例如。不易损坏,如果github上决定更改文件的格式,如果你使用一个不同的数据源等