python-3.x - 将 HTTP header 字典字符串加载到 JSON 中并解析它

标签 python-3.x ssl header python-requests http-headers

我将此 HTTP header 存储为字符串。我想以 JSON 格式加载它以便能够:

  1. 检查标题是否存在。

  2. 如果header不存在,我需要打印"no-header"

  3. 如果它存在,我需要检查某些选定指令的存在和内容。例如,如果找到 'Strict-Transport-Security',我需要检查它是否具有 max-age 指令。 max-age 是 1111。

如何做到这一点?我最初的尝试是:

import json


mystring="{'Server': 'nginx', 'Date': 'Fri, 19 Apr 2019 05:46:00 GMT', 'Content-Type': 'text/html; charset=cp1251', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload'}"
d = json.loads(mystring)

print(d['Strict-Transport-Security'])

我遇到了这个错误:

Traceback (most recent call last):   File "test.py", line 5, in
<module>
    d = json.loads(mystring)
   File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
   File "/usr/lib/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
   File "/usr/lib/python2.7/json/decoder.py", line 380, in raw_decode
    obj, end = self.scan_once(s, idx)
 ValueError: Expecting property name: line 1 column 2 (char 1)

我需要加载这个字符串格式(看起来像字典)并将其解析为:

  1. 检查 header 名称是否存在。

  2. 根据一些定义的标准检查其内容,例如包含、不包含等。

最佳答案

json 使用双引号而不是单引号,所以你可以替换它们:

mystring="{'Server': 'nginx', 'Date': 'Fri, 19 Apr 2019 05:46:00 GMT', 'Content-Type': 'text/html; charset=cp1251', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload'}"
mystring = mystring.replace("'", '"')
>>> print(json.loads(mystring))
{'Transfer-Encoding': 'chunked', 'Vary': 'Accept-Encoding', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html; charset=cp1251', 'Server': 'nginx', 'Connection': 'keep-alive', 'Date': 'Fri, 19 Apr 2019 05:46:00 GMT'}

或者您可以使用 ast.literal_eval :

import ast

d = ast.literal_eval(mystring)
>>> print(d['Date'])
Fri, 19 Apr 2019 05:46:00 GMT

关于python-3.x - 将 HTTP header 字典字符串加载到 JSON 中并解析它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56083811/

相关文章:

python - pickle - cPickle.UnpicklingError : invalid load key, '?'

ios - cmd 行测试因 SSL 证书错误而失败

ssl - 是否有任何好的说明来解密 SSL 流量?

gridview - Yii2 GridView 自定义标题行

csv - 如何使用camel-beanio跳过CSV标题行

header - MVC3 WebGrid 格式化或样式列标题

python - 一个类的多个实例同时被覆盖? (Python)

python-3.x - 不了解 sklearn 的 HashingVectorizer

python - 有没有一种好方法让一个类继承两个类之一

java - 使用 JSSE SSLEngine 进行 SSL session 管理