我有一些像这样的 json 文件:
{
"firstname": "John",
"lastname": "Doe",
"age": 25,
"profile": "/home/John/Pictures/john.png"
}
但我希望它更通用,而不是仅针对 John。 所以我想用 $HOME 替换“/home/John”。但这显然不适用于 json 文件。这是我尝试过的:
{
"firstname": "John",
"lastname": "Doe",
"age": 25,
"profile": "$HOME/Pictures/john.png"
}
我该如何解决这个问题?还是有别的办法?
谢谢。
最佳答案
要在 python3 中执行变量替换,请按照以下步骤操作。
将 JSON 文件中的“$HOME”更改为“${HOME}”。 JSON 文件如下所示:
{
"firstname": "John",
"lastname": "Doe",
"age": 25,
"profile": "${HOME}/Pictures/john.png"
}
下面的脚本说明了如何替换。
import os
import json
#Pass the above JSON file and create a file object
fileObj = open('nameOFJsonFile.json',)
#Convert JSON and parse as Python Dictionary
jsonDict = json.load(fileObj)
#Substitute the value wherever required using os.path.expandvars
jsonDict["profile"]=os.path.expandvars(jsonDict["profile"])
关于json - 如何在 json 文件中包含环境变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52028855/