Ilya Dachkovsky
Ilya Dachkovsky

Reputation: 405

How to pass a variable as a value in JSON

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?

Upvotes: 0

Views: 3544

Answers (2)

Chris Lindseth
Chris Lindseth

Reputation: 831

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}

Upvotes: 3

tdelaney
tdelaney

Reputation: 77337

There is no JSON here. JavaScript Object Notation is a serialized representation of data. Once you've deserialized it into python, its not JSON. When you did {some_variable_from_code} that's a python set with a single value. You could just do

{
    "customer_id": some_variable_from_code
}

After you've created the python dict, its serialzied to JSON for the call, but that happens under the covers.

Upvotes: 2

Related Questions