繁体   English   中英

在Python中传递JSON文档

[英]Passing a JSON document in Python

我正在尝试传递要编码为base64的策略文档。

策略文档位于~/policy_document

>>> policy = base64.b64encode(policy_document)

我需要做什么才能将policy_document传递给base64? 谢谢。

# 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

或者,如果您需要它来自当前用户的主文件夹,则可以添加对os.path.expanduser("~/policy_document")的调用

这为我工作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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