Search code examples
pythonpython-3.6string-interpolation

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.


Solution

  • 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