Reputation: 1615
I have some json file that looks like this:
{
"firstname": "John",
"lastname": "Doe",
"age": 25,
"profile": "/home/John/Pictures/john.png"
}
But i want it to be more general, not specific to John only. So i want to replace "/home/John" with like $HOME. But that doesn't work with json files apparently. Here's what i tried:
{
"firstname": "John",
"lastname": "Doe",
"age": 25,
"profile": "$HOME/Pictures/john.png"
}
How can I resolve this? Or is there another way?
Thanks.
Upvotes: 5
Views: 13452
Reputation: 742
To perform the variable substitution in python3 , follow the below steps.
Change "$HOME" to "${HOME}" in JSON file. The JSON file looks like below:
{
"firstname": "John",
"lastname": "Doe",
"age": 25,
"profile": "${HOME}/Pictures/john.png"
}
Below script indicates how to substitute.
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"])
Upvotes: 3