2015-05-26 156 views
2

我是新來的python,我需要解析一個JSON文件,它有HTTP響應標題,我需要找到一組特定的標題類型,使用或不。我JSON文件將是這樣的:如何解析Json文件並搜索特定的關鍵字集?

"2236": { 
    "status": "200 OK", 
    "x-request-id": "13e98a1c93205a532810b2d34c92a04d", 
    "x-powered-by": "Phusion Passenger 4.0.21", 
    "transfer-encoding": "chunked", 
    "set-cookie": "ip_country=IN; path=/; expires=Fri, 25-May-2035 06:54:09 GMT", 
    "expires": "Thu, 28 May 2015 06:54:10 GMT", 
    "vary": "Accept-Encoding", 
    "connection": "keep-alive", 
    "server": "nginx/1.2.1", 
    "x-runtime": "0.780037", 
    "etag": "\"0ac30791df0dae1e4723d5360e82cee4\"", 
    "x-ua-compatible": "IE=Edge,chrome=1", 
    "cache-control": "max-age=259200, public", 
    "date": "Mon, 25 May 2015 06:54:10 GMT", 
    "content-type": "text/html; charset=utf-8", 
    "x-rack-cache": "miss" 
}, 
"1681": { 
    "content-length": "56", 
    "accept-ranges": "bytes", 
    "vary": "Accept-Encoding,User-Agent", 
    "server": "PonyCakesv1.33.7", 
    "last-modified": "Fri, 22 May 2015 19:29:33 GMT", 
    "etag": "\"1c2665-2eb4-516b0ae026140\"", 
    "location": "http://www.olark.com/", 
    "date": "Mon, 25 May 2015 06:55:02 GMT", 
    "x-frame-options": "SAMEORIGIN", 
    "content-type": "text/html; charset=utf-8" 
} 

的數字是ID和我需要找到每個IDS使用'content-type' & 'x-frame-options'

我的輸出結果有被喜歡:

2236,content-type 
1681,content-type,x-frame-options 

如何實現這一目標?

+0

那你嘗試了嗎? –

回答

1

我的代碼:

import json 
json_data=open('INPUT_FLIX_DB.json') 
server_details = json.load(json_data) 
json_data.close() 
for id in server_details: 
    type=[] 
    if "content-type" in server_details[id]: 
     type.append("content-type") 
    if "x-frame-options" in server_details[id]: 
     type.append("x-frame-options") 
    print id,type 
+0

嗨Vignesh,非常感謝您的迴應。其實,我不需要像JSON的值'text/html; charset = utf-8'爲內容類型,而「SAMEORIGIN」爲「x-frame-options」,只要檢查ID是否有字符串'content-type'&'x-frame-options'! :2236,內容類型 1681,內容類型,x-frame-options –

+0

這是否正常工作,或者您需要特定文檔的所有密鑰的名稱 – The6thSense

+0

完美的傢伙!準確地獲得了期望它作爲輸出的密鑰和值!非常感謝 ;) –

2

嘗試這樣:

for key, value in my_json.iteritems(): 
    if any(x in value for x in ('content-type', 'x-frame-options')): 
     print key, x.get('content_type'), x.get('x-frame-options') 

如果聲明如果兩個或僅標題之一是,則返回true。

+0

你錯過了a)在if語句中,你能解釋一下上面的答案 – The6thSense

+0

是的,謝謝你的糾正。 –

+0

因此,如果有一個值不可用,並且您嘗試獲取該密鑰,它將不會顯示鍵值錯誤 – The6thSense

2

你沒有發佈你試過的東西,但似乎只是與json分析相關的東西。

你試過json模塊嗎?

+0

wesley請評論這種東西在評論區域,並只使用答案區域回答 – The6thSense

+0

哦,對不起: - ( – Wesley

相關問題