我需要将一个json文档写入一个文件。这是一个AWS的政策,是有点长,所以我有麻烦的格式
这是我遇到的问题:
def create_iam_policy(user_name):
# Set the date
today = datetime.today()
today = today.strftime("%m-%d-%Y")
# Set the output file
output_dir = "../../../json/iam"
output_file = output_dir + 'pol-aws-secrets-manager-' + user_name + today +'.json'
create_work_dir(output_dir)
policy_doc = "{
\"Version\": \"2012-10-17\",
\"Statement\": [
{
\"Effect\": \"Allow\",
\"Action\": [
\"secretsmanager:ListSecrets\",
\"secretsmanager:GetRandomPassword\"
],
\"Resource\": \"*\"
},
{
\"Effect\": \"Allow\",
\"Action\": [
\"kms:Decrypt\"
],
\"Resource\": \"arn:aws:kms:us-east-1:832839043616:key/24260438-1817-4e0b-897c-7f7958edba98\"
},
{
\"Effect\": \"Allow\",
\"Action\": [
\"kms:List*\"
],
\"Resource\": \"*\"
},
{
\"Effect\": \"Allow\",
\"Action\": [
\"secretsmanager:GetResourcePolicy\",
\"secretsmanager:GetSecretValue\",
\"secretsmanager:DescribeSecret\",
\"secretsmanager:ListSecretVersionIds\"
],
\"Resource\": \"*\",
\"Condition\": {
\"ForAnyValue:StringEquals\": {
\"secretsmanager:ResourceTag/Name\": user_name
}
}
}
]
}"
这是我正在使用的原始json文档:AWS Policy document
当我运行上述代码时,出现以下错误:
File ".\aws_iam_rotate_keys.py", line 261
policy_doc = "{
^
SyntaxError: EOL while scanning string literal
如何正确格式化这个长json文档,使其不会引发错误
创建一个dict,填充它并使用json dump将其保存到文件中
详见here
如果您真的想使用字符串文字,例如,您从其他地方获取JSON,并且不想麻烦地将其转换为Python对象,而只是将其转换回JSON,请使用三个引号,以便可以包含换行符
如果其中有反斜杠,也可以在开头加上
r
,以避免对所有内容进行双重转义。在这种情况下没有必要另一种方法是将JSON放在自己的文件中,让Python脚本读取它。这使得在必要时编辑JSON文件更加容易,因为您不必担心两种不同语言的语法
相关问题 更多 >
编程相关推荐