开发者

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 base6开发者_StackOverflow中文版4? 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")


This worked for me:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜