1

I try to pass a variable to nested JSON in Python script.

Script as below,

import requests, request

group = request.form['grp']
zon = request.form['zone']

load = { "extra_vars": {
                 "g_name": "' +str(group)+ '",
                 "z_name": "' +str(zon)+ '"
                 }
       }

----
--
-

However when i post the value to the API, it seem i post word '+str(group)+' and '+str(zon)+' instead the actual value that assign under declared variable.

Since i'm very new in Python programming, does passing value to nested JSON is allow in Python?

2 Answers 2

2

Try the following:

group = request.form['grp']
zon = request.form['zone']

load = { "extra_vars": {
                 "g_name": f"{group}",
                 "z_name": f"{zon}"
                 }
       }

Sign up to request clarification or add additional context in comments.

2 Comments

Indeed.. this is the great answer!!.. thank you so much
If you don't need to enclose group around a quote, then it's actually even easier to just use: "g_name": str(group) or "g_name": quote if quote is a string. No need for an f-string
2

You can pass variables into a string using f-strings and brackets around your variable (note {group}):

>>> group = "my_group"
>>> {"g_name": f"'{group}'"}
{'g_name': "'my_group'"}

Or doing simple string concatenation also, which is what you almost done in your code (but just did not properly close the ' character using "'":

>>> "'" + str(group) + "'"
"'my_group'"

All in all here's your code adapted:

load = { "extra_vars": {
                 "g_name": f"'{group}'",
                 "z_name": f"'{zon}'"
                 }
       }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.