Reputation: 112
I have a JSON file which I converted to a Dict that has something like
{
"a": "1",
"b": "2",
"c": "3"
}
and I want to format this string based on that JSON
"Blah {a} Blah Blah {b} {c}"
to output
"Blah 1 Blah Blah 2 3"
I haven't tried anything and I couldn't find anything by Googling it (Python how to format string based on json
), most results were just to pretty print JSON.
Upvotes: 1
Views: 2269
Reputation: 506
if you have the JSON array as a variable in your code like below
data = {
"a": "1",
"b": "2",
"c": "3"
}
You can then call those individual items based on the key name in the key/value pairs as defined in the data variable.
It can then be as simple as
new_string = "Blah " + str(data["a"]) + " blah blah " + str(data["b"]) + " " + str(data["c"])
The variable new_string will then be "Blah 1 blah blah 2 3"
I used the str() method just in case what was in the JSON array is not a string already.
If you are trying to be more programmatic about it, and the string will be generated many times with different data sets, you could do it similar to this, but with variable names that are meaningful to you and your project and made into a function.
data = {"a": "1", "b": "2", "c": "3"}
var_0 = str(data["a"])
var_1 = str(data["b"])
var_2 = str(data["c"])
new_string = "Blah " + var_0 + " blah blah " + var_1 + var_2
Then from there you can do whatever you need with the new_string
Upvotes: 0
Reputation: 22963
You can use str.format
to easily accomplish this. Assuming you've loaded you JSON data in memory as a dictionary:
>>> data = {
"a": "1",
"b": "2",
"c": "3"
}
>>> "Blah {a} Blah Blah {b} {c}".format(**data)
'Blah 1 Blah Blah 2 3'
if you're not sure how to load your JSON string into memory, use json.loads
:
>>> from json import loads
>>> data = loads('{ "a": "1", "b": "2", "c": "3" }')
>>> data
{'a': '1', 'b': '2', 'c': '3'}
So, put together, the complete script would be:
from json import loads
data = loads('{ "a": "1", "b": "2", "c": "3" }')
print("Blah {a} Blah Blah {b} {c}".format(**data))
Upvotes: 8