简体   繁体   中英

Python how to format a string based on dict or json object?

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.

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))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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