如何解析Json文件并搜索特定的关键字集?

时间:2015-05-26 05:57:48

标签: python json parsing

我是python的新手,我需要解析一个具有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,我需要找到每个ID使用'content-type' & 'x-frame-options'

我的输出结果是:

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

我如何实现这一目标?

3 个答案:

答案 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')

如果两个或只有一个标题值在值中,则if语句返回True。

答案 1 :(得分:1)

您没有发布您尝试过的内容,但似乎只是与json analyze相关的内容。

你试过json模块吗?

答案 2 :(得分: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