Reputation: 167
CRED_DATA = 'randomcred'
payload = "{\n \"password\": \"CRED_DATA\" ,\n \"username\": \"dom\\\\user\"\n}"
print(payload)
Output:
{
"password": "CRED_DATA" ,
"username": "dom\\user"
}
I tried double quotes, single quotes, { [ etc cannot figure it out . Is there a way to call the variable when inside the dict that is double quoted?
Upvotes: 0
Views: 1341
Reputation: 10440
You can try F-Strings in Python:
CRED_DATA = 'randomcred'
payload = F"{{\n \"password\": \"{CRED_DATA}\" ,\n \"username\": \"dom\\\\user\"\n}}"
print(payload)
Output:
{
"password": "randomcred" ,
"username": "dom\\user"
}
However, depending on the value of CRED_DATA
, this is not guaranteed to produce valid JSON (Thanks to @chepner). You can also use dict
and json.dumps()
in Python as already mentioned in the other answer.
Upvotes: 1
Reputation: 145
You payload variable is not a dictionary, it is a string. I suppose you want to sort of serialize iot for sending over the network or something - it would help if you elaborated your intent.
In any case: If you want python to resolve the variable in your string, try something like:
payload = "{\n \"password\": \"" + CRED_DATA + "\" ,\n \"username\": \"dom\\\\user\"\n}"
...But I personally think it would be better to use a dictionary, and json.dumps to achieve this:
import json
CRED_DATA = 'randomcred'
payload = {
"password": CRED_DATA,
"username": "dom user"
}
print(json.dumps(payload, indent=4, sort_keys=True))
Again. Depending on your use case which is not clear from the question.
Upvotes: 0
Reputation: 19
do you mean this?
CRED_DATA = 'randomcred'
payload = "password:",CRED_DATA
payload2 = ("\n \"username\": \"dom\\\\user\"\n}")
print(payload)
print(payload2)
Upvotes: 0
Reputation: 531993
Generate the JSON properly, using a dict
and json.dump
.
CRED_DATA = 'randomcred'
payload = {'password': CRED_DATA, 'username': r'dom\user'}
print(json.dumps(payload))
If you are getting the JSON value from somewhere else, decode it first, update the resulting dict
, and then dump it again.
payload = json.loads(payload)
payload['password'] = CRED_DATA
payload = json.dumps(payload)
Upvotes: 3