【问题标题】:How to Parse a Json file and search for specific set of key words?如何解析 Json 文件并搜索特定的关键字集?
【发布时间】:2015-05-26 05:57:47
【问题描述】:

我是 python 新手,我需要解析一个 JSON 文件,其中包含 HTTP 响应标头,我需要找到一组特定的标头类型,这些标头类型是否被使用。我的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

我如何做到这一点?

【问题讨论】:

  • 你已经尝试了什么?

标签: python json parsing


【解决方案1】:

试试这样的:

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。

【讨论】:

  • 你在if语句中漏掉了一个),你能解释一下上面的答案吗
  • 因此,如果一个值不可用,并且如果您尝试获取该键,它将不会显示键值错误
  • 不,如果其中一个标题丢失,它会打印“无”。我认为会更好,因为您可以定义按位置打印的标题。
  • 据我了解,作者希望过滤对象没有必需的标题。
【解决方案2】:

我的代码:

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

【讨论】:

  • 嗨 Vignesh,非常感谢您的回复。实际上,我不需要像 'text/html; 这样的 JSON 值。 charset=utf-8' 用于内容类型,“SAMEORIGIN”用于“x-frame-options”。只需检查 ID 是否有字符串 'content-type' & 'x-frame-options' !示例:2236,content-type 1681,content-type,x-frame-options
  • 这是否有效,或者您需要特定文档的所有键的名称
  • 完美的家伙!准确地得到了我期望它作为输出的键和值!非常感谢;)
【解决方案3】:

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

你试过json模块吗?

【讨论】:

  • wesley这种东西请在评论区评论,只用回答区回答
  • 哦,很抱歉:-(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-12
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 2015-10-04
  • 2015-11-13
  • 2023-03-07
相关资源
最近更新 更多