【问题标题】:Converting unicode to string with " "使用“”将 unicode 转换为字符串
【发布时间】:2019-08-01 12:27:03
【问题描述】:

我目前正在编写使用 aws cli 和 python 删除 aws 资源的脚本。作为脚本的一部分,我必须删除安全组的规则。我采用的方法是执行describe-security-groups 命令,并且能够将以下值存储在变量中:

[{u'IpProtocol':u'-1',u'PrefixListIds':[],u'IpRanges':[{u'CidrIp':u'0.0.0.0/0'}],u'UserIdGroupPairs':[],u'Ipv6Ranges':[]}]

但是,为了将此值传递给revoke-security-group-egress 命令,我需要以下形式:

[{"IpProtocol":"-1","PrefixListIds":[],"IpRanges":[{"CidrIp":"0.0.0.0/0"}],"UserIdGroupPairs":[],"Ipv6Ranges":[]}]

我正在寻找一种方法,该方法也可用于具有不同结构的其他列表。

或者还有其他方法可以使用 aws cli 和 python 删除安全组的所有规则吗?

--更新--

在阅读here的答案后,我找到了接近我想要的方法

【问题讨论】:

  • 我认为那里的编码应该无关紧要......
  • 听起来您想要生成 JSON,而不是 Python 字典的 repr。你试过json 模块吗?
  • 我收到以下错误:期望用双引号括起来的属性名称。所以,值应该在 " "
  • 只要使用 Python 3.x 就可以了,在处理 Unicode 时会省去很多麻烦。
  • @ForceBru 我需要使用 Python2.7。所以,我必须处理它。

标签: python python-2.7 aws-cli aws-security-group


【解决方案1】:

这可能有点矫枉过正,但你可以这样做:

import ast

# if your data comes in as an actual list, convert it to a string
data = "[{u'IpProtocol':u'-1',u'PrefixListIds':[],u'IpRanges':[{u'CidrIp':u'0.0.0.0/0'}],u'UserIdGroupPairs':[],u'Ipv6Ranges':[]}]"

AST = ast.parse(data, mode='eval')

for node in ast.walk(AST):
    if isinstance(node, ast.Str):
        node.s = str(node.s) # replace `unicode` with `str`

res = ast.literal_eval(AST)

res == [{'IpProtocol': '-1', 'Ipv6Ranges': [], 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'UserIdGroupPairs': [], 'PrefixListIds': []}]

Docs on the ast module。这也适用于 Python 3。

如果您确切知道数据的结构(您的字典可以有哪些值,有多少个字典),您可以遍历字典(以及列表中的每个字典)的每个键和值并更改unicodestr 类型的所有内容。这可能会更麻烦,但可能会更快。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-11-03
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多