Как объединить строки json

#json #python-3.x #amazon-web-services

#json #python-3.x #amazon-веб-сервисы

Вопрос:

Я пытаюсь создать агрегированную политику корзины. Я извлекаю существующую политику корзины и добавляю конкретное утверждение, чтобы сделать его более округлым. Однако мне интересно, каков наилучший способ добиться этого?

Вот исходная строка, содержащая политику:

 {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1565731301209",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::1234567890:role/RoleforLambdafunctiondatabunker"
            },
            "Action": "s3:ListBucket",
            "Resource": "arn:aws:s3:::demo-reko-gaurav",
            "Condition": {
                "StringLike": {
                    "aws:UserAgent": "*AWS_Lambda_python*"
                }
            }
        },
        {
            "Sid": "Stmt34",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::1234567890:role/RoleforLambdafunctiondatabunker"
            },
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::demo-reko-gaurav/*",
            "Condition": {
                "StringLike": {
                    "aws:UserAgent": "*AWS_Lambda_python*"
                }
            }
        }
    ]
}
  

и я хочу добавить приведенные ниже строки в раздел инструкции вышеупомянутой политики:

 {
    "Sid": "AllowSSLRequestsOnly",
    "Effect": "Deny",
    "Principal": "*",
    "Action": "s3:*",
    "Resource": [
        "arn:aws:s3:::tests3grvtest",
        "arn:aws:s3:::tests3grvtest/*"
    ],
    "Condition": {
        "Bool": {
            "aws:SecureTransport": "false"
        }
    }
}
  

Какой самый простой и эффективный способ сделать это в Python?

Ответ №1:

Вы можете использовать json из стандартной библиотеки python.

 import json

policy = """{"Version":"2012-10-17","Statement":[{"Sid":"Stmt1565731301209","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::1234567890:role/RoleforLambdafunctiondatabunker"},"Action":"s3:ListBucket","Resource":"arn:aws:s3:::demo-reko-gaurav","Condition":{"StringLike":{"aws:UserAgent":"AWS_Lambda_python"}}},{"Sid":"Stmt34","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::1234567890:role/RoleforLambdafunctiondatabunker"},"Action":"s3:PutObject","Resource":"arn:aws:s3:::demo-reko-gaurav/*","Condition":{"StringLike":{"aws:UserAgent":"AWS_Lambda_python"}}}]}"""
add_policy ="""{"Sid": "AllowSSLRequestsOnly","Effect": "Deny","Principal": "","Action": "s3:","Resource": ["arn:aws:s3:::tests3grvtest","arn:aws:s3:::tests3grvtest/*"],"Condition": {"Bool": {"aws:SecureTransport": "false"}}}"""

pol_json = json.loads(policy)
add_pol_json = json.loads(add_policy)

pol_json['Statement'].append(add_pol_json)
pol_json

new_policy_string = json.dumps(pol_json)
new_policy_string
  

ВОЗВРАТ:

 {'Version': '2012-10-17',
 'Statement': [{'Sid': 'Stmt1565731301209',
   'Effect': 'Allow',
   'Principal': {'AWS': 'arn:aws:iam::1234567890:role/RoleforLambdafunctiondatabunker'},
   'Action': 's3:ListBucket',
   'Resource': 'arn:aws:s3:::demo-reko-gaurav',
   'Condition': {'StringLike': {'aws:UserAgent': 'AWS_Lambda_python'}}},
  {'Sid': 'Stmt34',
   'Effect': 'Allow',
   'Principal': {'AWS': 'arn:aws:iam::1234567890:role/RoleforLambdafunctiondatabunker'},
   'Action': 's3:PutObject',
   'Resource': 'arn:aws:s3:::demo-reko-gaurav/*',
   'Condition': {'StringLike': {'aws:UserAgent': 'AWS_Lambda_python'}}},
  {'Sid': 'AllowSSLRequestsOnly',
   'Effect': 'Deny',
   'Principal': '',
   'Action': 's3:',
   'Resource': ['arn:aws:s3:::tests3grvtest', 'arn:aws:s3:::tests3grvtest/*'],
   'Condition': {'Bool': {'aws:SecureTransport': 'false'}}}]}
  

Ответ №2:

Использование python json , вероятно, самое простое. Вам просто нужно загрузить json как словари и обновить словарь по своему усмотрению.

 policy = json.loads('{"Version":"2012-10-17","Statement":[{"Sid":"Stmt1565731301209","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::1234567890:role/RoleforLambdafunctiondatabunker"},"Action":"s3:ListBucket","Resource":"arn:aws:s3:::demo-reko-gaurav","Condition":{"StringLike":{"aws:UserAgent":"AWS_Lambda_python"}}},{"Sid":"Stmt34","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::1234567890:role/RoleforLambdafunctiondatabunker"},"Action":"s3:PutObject","Resource":"arn:aws:s3:::demo-reko-gaurav/*","Condition":{"StringLike":{"aws:UserAgent":"AWS_Lambda_python"}}}]}')

new_statement = json.loads('{"Sid": "AllowSSLRequestsOnly","Effect": "Deny","Principal": "","Action": "s3:","Resource": ["arn:aws:s3:::tests3grvtest","arn:aws:s3:::tests3grvtest/*"],"Condition": {"Bool": {"aws:SecureTransport": "false"}}}')

policy["Statement"].append(new_statement)

policy_str = json.dumps(policy)
  

Ответ №3:

Это довольно просто :

 policy = {"Version":"2012-10-17","Statement":[{"Sid":"Stmt1565731301209","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::1234567890:role/RoleforLambdafunctiondatabunker"},"Action":"s3:ListBucket","Resource":"arn:aws:s3:::demo-reko-gaurav","Condition":{"StringLike":{"aws:UserAgent":"AWS_Lambda_python"}}},{"Sid":"Stmt34","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::1234567890:role/RoleforLambdafunctiondatabunker"},"Action":"s3:PutObject","Resource":"arn:aws:s3:::demo-reko-gaurav/*","Condition":{"StringLike":{"aws:UserAgent":"AWS_Lambda_python"}}}]}

new_statement = {"Sid": "AllowSSLRequestsOnly","Effect": "Deny","Principal": "","Action": "s3:","Resource": ["arn:aws:s3:::tests3grvtest","arn:aws:s3:::tests3grvtest/*"],"Condition": {"Bool": {"aws:SecureTransport": "false"}}}

policy['Statement'].append(new_statement)