I would personally do something like this:

import json
import datetime

today = datetime.date.today()
tomorrow = today + datetime.timedelta(days = 1)

data = [{
    "date": str(tomorrow),
    "price": {
        "amount": 15100
    }
}]

print(json.dumps(data))

Of course, after this, you can do anything you want with json.dumps(data): in your case, send it in a request.

Answer from BrownieInMotion on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › json, strings, and f-strings
r/learnpython on Reddit: Json, strings, and f-strings
March 24, 2022 -

I'm stumped on how to fix this.

import json
import os

awx_base_url = "https://127.0.0.1”
inventory_name = "VCenter - POC”

build_number = 15
deploy_frontend = 'true'


to_deploy_dict = [

    {
        "name": " TEST”,
        "cmd": f"awx job_templates launch --inventory '{inventory_name}' --extra_vars '{{ build_number: {build_number}, deploy_frontend: {deploy_frontend} }}' 14",
     },
]

for item in to_deploy_dict:

    print("Executing: " + item["cmd"])
    if "workflow" in item["cmd"]:
          jobid = json.loads(os.popen(item["cmd"]).read())["id"]

The cli returns this error: {'variables_needed_to_start': ["Value True for 'deploy_frontend' expected to be one of ['true', 'false']."]}

Bypassing my script and using the cli directly, this command is successful.

 awx job_templates launch --inventory 'VCenter - POC' --extra_vars build_number: 15, deploy_frontend: 'true', 15 

What is getting lost in translation here?

Discussions

Python - parsing JSON and f string - Stack Overflow
I am trying to write a small JSON script that parses JSON files. I need to include multiple variables in the code but currently, I'm stuck since f string does not seem to be working as I expected. ... More on stackoverflow.com
🌐 stackoverflow.com
python - using variable (f)-string stored in json - Stack Overflow
f-string work by substituting the ... file is json so you can't keep variables there thatswhy f-string is not working previously. Here also firstly we get the string and then we are saying it to evaluate the f-string here using variables initialised in this file. 2022-10-19T08:17:44.723Z+00:00 ... I found out another loophole with the f-string eval method. It cannot parse multiline strings (strings that contain an '\n' character). Which again suggests us to use the format ... More on stackoverflow.com
🌐 stackoverflow.com
python - how to use fstring in a complex json object - Stack Overflow
I am trying to change the \"from\": ... embedded strings are making it somewhat difficult when using fstring. I am also open to any alternative ideas other than fstrings if it fixes the problem ... variables is itself a nested JSON object. Just use json.loads to convert that to a Python dict, then ... More on stackoverflow.com
🌐 stackoverflow.com
python - String format a JSON string gives KeyError - Stack Overflow
You'd be better off just using Python dictionaries and then using json.dumps() to output the JSON format. 2023-08-23T21:35:40.783Z+00:00 ... Find the answer to your question by asking. More on stackoverflow.com
🌐 stackoverflow.com
October 20, 2020
🌐
Marketcalls
marketcalls.in › home › mastering python f-string formatting: a trader’s guide
Mastering Python F-String Formatting: A Trader’s Guide
November 15, 2023 - json.loads is used to parse the JSON string into a Python object (in this case, a list of dictionaries). An f-string is used within a loop to format and print out each stock’s symbol and price.
🌐
Real Python
realpython.com › python-f-strings
Python's F-String for String Interpolation and Formatting – Real Python
November 30, 2024 - Python's f-strings provide a readable way to interpolate and format strings. They're readable, concise, and less prone to error than traditional string interpolation and formatting tools, such as the .format() method and the modulo operator ...
🌐
Mimo
mimo.org › glossary › python › formatted-strings
Python Formatted Strings / f-string formatting Guide
f-strings also support JSON-friendly representations using repr, which ensures that objects are formatted in a readable string form. ... f-strings can include more than variables and values. They can include expressions, function calls, and even conditional logic: ... Python's so-called format ...
Find elsewhere
🌐
ReqBin
reqbin.com › code › python › trs5wpc0 › python-f-string-example
How to format string with f-string in Python?
July 27, 2023 - To create an f-string, add the letter "f" or "F" before the opening quotes of your string. To print the variable value in the formatted string, you must specify the variable name inside a curly brace "{}". At runtime, all variable names will ...
🌐
GeeksforGeeks
geeksforgeeks.org › json-formatting-python
JSON Formatting in Python - GeeksforGeeks
August 23, 2023 - Some of them are; 1) Using % 2) Using {} 3) Using Template Strings In this article the formatting using % is discussed. The formatting using % is similar to that of 'printf' in C programming language. %d - integer %f - ... Orjson is a third-party Python library that provides a fast and efficient implementation of JSON encoding and decoding.
🌐
TutorialsPoint
tutorialspoint.com › json-formatting-in-python
Python - JSON
June 26, 2020 - encode(obj) − Serializes a Python object into a JSON formatted string.
Top answer
1 of 3
77

You need to double the outer braces; otherwise Python thinks { "File".. is a reference too:

output_format = '{{ "File": "{filename}", "Success": {success}, "ErrorMessage": "{error_msg}", "LogIdentifier": "{log_identifier}" }}'

Result:

>>> print output_format.format(filename='My_file_name',
...                            success=True,
...                            error_msg='',
...                            log_identifier='123')
{ "File": "My_file_name", "Success": True, "ErrorMessage": "", "LogIdentifier": "123" }

If, indicentally, you are producing JSON output, you'd be better off using the json module:

>>> import json
>>> print json.dumps({'File': 'My_file_name',
...                   'Success': True,
...                   'ErrorMessage': '',
...                   'LogIdentifier': '123'})
{"LogIdentifier": "123", "ErrorMessage": "", "Success": true, "File": "My_file_name"}

Note the lowercase true in the output, as required by the JSON standard.

2 of 3
4

As mentioned by Tudor in a comment to another answer, the Template class was the solution that worked best for me. I'm dealing with nested dictionaries or list of dictionaries and handling those were not as straightforward.

Using Template though the solution is quite simple.

I start with a dictionary that is converted into a string. I then replace all instances of { with ${ which is the Template identifier to substitute a placeholder.

The key point of getting this to work is using the Template method safe_substitute. It will replace all valid placeholders like ${user_id} but ignore any invalid ones that are part of the dictionary structure, like ${'name': 'John', ....

After the substitution is done I remove any leftovers $ and convert the string back to a dictionary.

In the code bellow, resolve_placeholders returns a dictionary where each key matches a placeholder in the payload string and the value is substituted by the Template class.

from string import Template
.
.
.
payload = json.dumps(payload)
payload = payload.replace('{', '${')
replace_values = self.resolve_placeholders(payload)
if replace_values:
    string_template = Template(payload)
    payload = string_template.safe_substitute(replace_values)
payload = payload.replace('${', '{')
payload = json.loads(payload)
🌐
GeeksforGeeks
geeksforgeeks.org › formatted-string-literals-f-strings-python
f-strings in Python - GeeksforGeeks
June 19, 2024 - To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str.format(). F-strings provide a concise and convenient way to embed Python expressions inside string ...
🌐
Python documentation
docs.python.org › 3 › tutorial › inputoutput.html
7. Input and Output — Python 3.14.6 documentation
Numbers take a bit more effort, since the read() method only returns strings, which will have to be passed to a function like int(), which takes a string like '123' and returns its numeric value 123. When you want to save more complex data types like nested lists and dictionaries, parsing and serializing by hand becomes complicated. Rather than having users constantly writing and debugging code to save complicated data types to files, Python allows you to use the popular data interchange format called JSON (JavaScript Object Notation).
🌐
EDUCBA
educba.com › home › software development › software development tutorials › python tutorial › python json to string
Python JSON to string | Working & examples of Python JSON to string
April 3, 2023 - There are two ways of converting JSON to string in Python; one way is to use json method dumps(), and another way is to use an API such as requests module in Python. In the below section, let us demonstrate these two ways with examples.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
freeCodeCamp
freecodecamp.org › news › python-f-strings-tutorial-how-to-use-f-strings-for-string-formatting
Python f-String Tutorial – String Formatting in Python Explained with Code Examples
September 14, 2021 - When you're formatting strings in Python, you're probably used to using the format() method. But in Python 3.6 and later, you can use f-Strings instead. f-Strings, also called formatted string literals, have a more succinct syntax and can be super h...
🌐
Databricks
community.databricks.com › t5 › get-started-discussions › using-f-strings-in-filenames-to-read-in-files-from-mounted › td-p › 36171
Using F Strings in filenames to read in files from... - Databricks Community - 36171
July 4, 2023 - Using F Strings in filenames to read in files from... ... Below are 2 versions of codes I tried and the failure messages. Does anyone have advice how to form this properly? ... for x in range(2,num_organization_page,1): file_str = f"dbfs:/mnt/dlsi2023/raw/ds_pet_finder_organization{x}.json", print(file_str) organizations_df = spark.read.option("multiline","true").json(f"{file_str}")