简体   繁体   中英

Passing a JSON document in Python

I am trying to pass a policy document to be encoded into base64.

The policy document is located at ~/policy_document

>>> policy = base64.b64encode(policy_document)

What do I need to do here to get policy_document to pass it to base64? Thank you.

# First open the file
# Then read the entire contents into memory
>>> policy_document = open("/absolute/path/to/policy_document", "r").read()

# Then base64 encode the contents.
>>> policy = base64.b64encode(policy_document)

# If you are using Python 2.7 you can use the with statement
# to ensure files are cleaned up
# (See @Niklas' comment)
>>> with open("/absolute/path/to/policy_document", "r") as fp:
...     policy_document = fp.read()
...      policy = base64.b64encode(policy_document)
# fp will be properly closed

Alternately, if you need it to be from the current user's home folder you could add a call to os.path.expanduser("~/policy_document")

这为我工作:

policy = base64.b64encode(json.JSONEncoder().encode({dict})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM