2011-03-03 132 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上決定更改文件的格式,如果你使用一個不同的數據源等