Home > OS >  Python Dictionary Replace String Template
Python Dictionary Replace String Template

Time:09-23

I'm trying to populate a JSON string with a Python Dictionary:

dictionary = {}
dictionary['bucket1'] = 'bucket1a'
dictionary['bucket2'] = 'bucket2b'
dictionary['bucket3'] = 'bucket3c'

mystring = "\t{\n\t\t\"Effect\": \"Allow\",\n\t\t\"Action\": [\"s3:*\"],\n\t\t\"Resource\": [\n"
for k,v in dictionary.items():
    mystring =str(f"\t\t\t\"arn:aws:s3:::{k}\",\n")
    mystring =str(f"\t\t\t\"arn:aws:s3:::{k}/*\",\n")
mystring =str("\t\t]\n\t}")
print(mystring)

My issue is that the last replacement ends with a , which breaks the JSON formatting:

    {
        "Effect": "Allow",
        "Action": ["s3:*"],
        "Resource": [
            "arn:aws:s3:::bucket1",
            "arn:aws:s3:::bucket1/*",
            "arn:aws:s3:::bucket2",
            "arn:aws:s3:::bucket2/*",
            "arn:aws:s3:::bucket3",
            "arn:aws:s3:::bucket3/*",
        ]
    }

I want to be able to handle dynamic dictionaries. Is there a better way to handle this transformation and/or more natural handling of JSON from a dictionary in Python?

CodePudding user response:

There is a built in json module (import json). Use json.dumps(dictionary) to obtain a JSON formatted string of the given dictionary argument. For prettier formatting, use json.dumps(dictionary, indent=2).

CodePudding user response:

Try this:
import json


dictionary = {'bucket1': 'bucket1a',
              'bucket2': 'bucket2b',
              'bucket3': 'bucket3c'}

stmt = {'Effect': 'Allow', 'Action': ['s3: *'], 'Resource': []}

# Only need to iterate over keys it seems, so we don't need to
# access the `dictionary.items()` method
for k in dictionary:
    stmt['Resource'].append(f'arn:aws:s3:::{k}')
    stmt['Resource'].append(f'arn:aws:s3:::{k}/*')

mystring = json.dumps(stmt, indent=2)

print(mystring)
Explanation:

As mentioned, there's no need to work with strings. You can instead append elements directly to the Resource key, which is a list object. Then, if you want a valid formatted JSON string, you can instead use the built in json.dumps method and pass in your Python dict object which contains the policy statement definition.

Output:
{
  "Effect": "Allow",
  "Action": [
    "s3: *"
  ],
  "Resource": [
    "arn:aws:s3:::bucket1",
    "arn:aws:s3:::bucket1/*",
    "arn:aws:s3:::bucket2",
    "arn:aws:s3:::bucket2/*",
    "arn:aws:s3:::bucket3",
    "arn:aws:s3:::bucket3/*"
  ]
}
  • Related