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.
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?
Python - parsing JSON and f string - Stack Overflow
python - using variable (f)-string stored in json - Stack Overflow
python - how to use fstring in a complex json object - Stack Overflow
python - String format a JSON string gives KeyError - Stack Overflow
you should use string.format() instead of f-strings
Still if you want to use f-strings then you should use eval like this, its unsafe
DAY="1"
MONTH="12"
df = pd.DataFrame(
[{
"path":"home/data/month={MONTH}/day={DAY}"
},
{
"path":"home/data/month={MONTH}/day={DAY}"
}
]
)
a = df['path'][0]
print(eval(f"f'{a}'"))
#home/data/month=12/day=1
Thanks to Deepak Tripathi answer, the answer is to use string format. Like this:
day="1"
month="12"
conf_path=pandas.read_json("...")
path=conf_path["path"]
data=spark.read_parquet(path.format(MONTH=month, DAY=day))
This answer was posted as an edit to the question using variable (f)-string stored in json by the OP Florida Man under CC BY-SA 4.0.
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.
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)
{} has special meaning in str.format (place holder and variable name), if you need literal {} with format, you can use {{ and }}:
TODO_JSON = '{{"id": {0},"title": {1},"completed:" {2}}}'
print(TODO_JSON.format(42, 'Some Task', False))
# {"id": 42,"title": Some Task,"completed:" False}
You can use % formatting style.
TODO_JSON = '{"id": %i,"title": %s,"completed:" %s}'
print(TODO_JSON % (42, 'Some Task', False))
If you are using 2.6+, you can use do this:
print json.dumps(jsonStr, sort_keys=True, indent=2, separators=(',', ': '))
http://docs.python.org/2/library/json.html
For Python as well as JSON, the order within a dict bears no meaning. Use lists instead of dicts if you mind.
If you only want to order the JSON output (that is, prefer {1:0, 2:0} over {2:0, 1:0}, even if they are equivalent), you can use the collections.OrderedDict which will remember the order the items were inserted.