Issue
It is possible to place any variable from a code in SQL queries, for example:
sqlalchemy_query= f'''
order_id,
order_sum
from some_table_name
where customer_id ={some_variable}
'''
As you can see everything is simple here: f-string, my variable in curly brackets. Nice, simple, and it works.
However, curly brackets in a similar JSON query for noSQL DB did not work for me. I was using elasticsearch Python Client with queries in JSON.
{
...
"customer_id": {some_variable_from_code}
...
}
So how can I pass variables inside JSON strings in Python?
Is there any character I need to escape, like in .NET?
Solution
If your query formatted as an f string contains literal curly braces you would need to double the curly braces in this case:
some_variable_from_code = "foo"
query_string = f"""{{"customer_id": {some_variable_from_code}}}"""
print(query_string)
Results in:
{"customer_id": foo}
Answered By - Chris Lindseth
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.