我想将标题字符串转换为字典。字符串来自各种来源,因此格式有点复杂。
这是一个例子:
import ast
import re
header="{'Content-Type': 'text/html', 'Content-Security-Policy': "default-src 'self'; img-src 'self' https://www.google.com/ https://www.google-analytics.com/ https://stats.g.doubleclick.net/; form-action 'self' https://agilemail.createsend.com/ https://www.createsend.com/t/subscribeerror https://www.createsend.com/t/securedsubscribe; frame-src https://www.youtube-nocookie.com/; connect-src 'self'", 'X-Content-Type-Options': 'nosniff', 'X-Amz-Cf-Id': 'XZOj8R9YBVEMbHv93beUYFIizxUbrGKL_LVrS1gjMF-86I8mgtNFYw=='}"
headerDict = ast.literal_eval(header)
当我运行它时,我得到这个错误:
SyntaxError: invalid syntax
我更改了字符串中的两个双引号:"default-src [...] https://a.1password.eu/"
from "
到 ""
但是还是有错误。显然来自包含单引号的 'self'
的内容。
我根本不应该更改标题内容。但是,如果我应用单个规则,例如,将每个 "
替换为 ""
这是可能的解决方案。因为我需要解析 header 。它应该保持其原始状态数据,我不应该更改任何内容。
这种情况下的解决方案是什么?这是一个示例,但我希望看到其他变体。如何将类似字典的字符串转换成字典?
最佳答案
使用三引号字符串:
import ast
header = """{'Content-Type': 'text/html', 'Content-Security-Policy': "default-src 'self'; img-src 'self' https://www.google.com/ https://www.google-analytics.com/ https://stats.g.doubleclick.net/; form-action 'self' https://agilemail.createsend.com/ https://www.createsend.com/t/subscribeerror https://www.createsend.com/t/securedsubscribe; frame-src https://www.youtube-nocookie.com/; connect-src 'self'", 'X-Content-Type-Options': 'nosniff', 'X-Amz-Cf-Id': 'XZOj8R9YBVEMbHv93beUYFIizxUbrGKL_LVrS1gjMF-86I8mgtNFYw=='}"""
ast.literal_eval(header)
输出:
{'Content-Type': 'text/html',
'Content-Security-Policy': "default-src 'self'; img-src 'self' https://www.google.com/ https://www.google-analytics.com/ https://stats.g.doubleclick.net/; form-action 'self' https://agilemail.createsend.com/ https://www.createsend.com/t/subscribeerror https://www.createsend.com/t/securedsubscribe; frame-src https://www.youtube-nocookie.com/; connect-src 'self'",
'X-Content-Type-Options': 'nosniff',
'X-Amz-Cf-Id': 'XZOj8R9YBVEMbHv93beUYFIizxUbrGKL_LVrS1gjMF-86I8mgtNFYw=='}
关于Python 请求 header 。如何解析这个? ast 的语法无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56085899/