Reputation: 935
I've some JSON data:
data = '''
{
"test": "{{{test}}}"
}
'''
Now I want to replace "{{{test}}}"
with {{{test}}}
(so without quotes).
Hardcoded it works:
new = data.replace("\"{{{test}}}\"", "{{{test}}}")
print(new)
output:
{
"test": {{{test}}}
}
But I need to import the 'test' as variable in the command so I tried:
variable = "test"
new = data.replace("\"{{{%s}}}\"", "{{{%s}}}" % variable)
print(new)
But then I got the quotes again:
{
"test": "{{{test}}}"
}
What am I doing wrong and how can I make this work?
Upvotes: 0
Views: 232
Reputation: 17960
Your issue is here:
new = data.replace("\"{{{%s}}}\"", "{{{%s}}}" % variable)
You're only doing the string substitution on the second value.
Here's a way that might be cleaner:
substitution = "{{{%s}}}" % variable
new = data.replace('"%s"' % substitution, substitution)
That being said if you're doing extensive string munging like this, you may want to look into a templating library like Jinja or a compile-to-JSON language like Jsonnet. I personally prefer Jsonnet, but to each their own.
Upvotes: 1