简体   繁体   中英

Python 3.6 - Literal string interpolation using JSON

I am trying to read a JSON file, which includes Python variables, which should be shown as the value of the variable and not as the variable itself.

with open('path_to_file.json') as f:
           my_json = json.load(f)

json_variable = my_json['text']

# The example text in the json file is:
# Hello, I want to be there in {defined_days} days

defined_days = 3

# What I tried, but doesn't work
interpolated_text = f'{json_variable}'

# Output of interpolated_text:
# Hello, I want to be there in {defined_days} days

It shows the string from the json file, but defined_days will not be replaced with the number 3 .

Since your format string is in a variable, you'll need to use the format method instead of f-strings

json_variable = 'Hello, I want to be there in {defined_days} days'

defined_days = 3

interpolated_text = json_variable.format(**locals())

print(interpolated_text)

Output:

Hello, I want to be there in 3 days

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